44 #include "llvm/ADT/ScopeExit.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/STLExtras.h"
47 #include "llvm/ADT/StringExtras.h"
52 using namespace clang;
64 class CheckDefaultArgumentVisitor
67 const Expr *DefaultArg;
70 CheckDefaultArgumentVisitor(
Sema &S,
const Expr *DefaultArg)
71 : S(S), DefaultArg(DefaultArg) {}
76 bool VisitLambdaExpr(
const LambdaExpr *Lambda);
81 bool CheckDefaultArgumentVisitor::VisitExpr(
const Expr *
Node) {
82 bool IsInvalid =
false;
83 for (
const Stmt *SubStmt :
Node->children())
84 IsInvalid |= Visit(SubStmt);
91 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(
const DeclRefExpr *DRE) {
94 if (!isa<VarDecl, BindingDecl>(
Decl))
97 if (
const auto *Param = dyn_cast<ParmVarDecl>(
Decl)) {
108 diag::err_param_default_argument_references_param)
109 << Param->getDeclName() << DefaultArg->getSourceRange();
110 }
else if (
auto *VD =
Decl->getPotentiallyDecomposedVarDecl()) {
125 diag::err_param_default_argument_references_local)
132 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(
const CXXThisExpr *ThisE) {
137 diag::err_param_default_argument_references_this)
141 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
146 if (
const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
147 E = OVE->getSourceExpr();
148 assert(E &&
"pseudo-object binding without source expression?");
156 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(
const LambdaExpr *Lambda) {
165 return S.
Diag(LC.getLocation(), diag::err_lambda_capture_default_arg);
167 auto *D = cast<VarDecl>(LC.getCapturedVar());
168 Invalid |= Visit(D->getInit());
200 llvm_unreachable(
"should not see unresolved exception specs here");
229 "should not generate implicit declarations for dependent cases");
233 assert(EST ==
EST_Dynamic &&
"EST case not considered earlier.");
235 "Shouldn't collect exceptions when throw-all is guaranteed.");
240 Exceptions.push_back(E);
268 if (Self->canThrow(S))
275 diag::err_typecheck_decl_incomplete_type))
290 if (Result.isInvalid())
292 Arg = Result.getAs<
Expr>();
294 CheckCompletedExpr(Arg, EqualLoc);
307 UnparsedDefaultArgInstantiationsMap::iterator InstPos
310 for (
unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
311 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
324 if (!param || !DefaultArg)
338 Diag(EqualLoc, diag::err_param_default_argument)
352 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
360 if (Result.isInvalid())
363 DefaultArg = Result.getAs<
Expr>();
366 CheckDefaultArgumentVisitor DefaultArgChecker(*
this, DefaultArg);
367 if (DefaultArgChecker.Visit(DefaultArg))
419 if (MightBeFunction) {
423 MightBeFunction =
false;
426 for (
unsigned argIdx = 0, e = chunk.
Fun.
NumParams; argIdx != e;
430 std::unique_ptr<CachedTokens> Toks =
433 if (Toks->size() > 1)
435 Toks->back().getLocation());
447 MightBeFunction =
false;
454 return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
464 bool Invalid =
false;
475 for (; PrevForDefaultArgs;
523 for (
unsigned p = 0, NumParams = PrevForDefaultArgs
526 p < NumParams; ++p) {
530 bool OldParamHasDfl = OldParam ? OldParam->
hasDefaultArg() :
false;
533 if (OldParamHasDfl && NewParamHasDfl) {
534 unsigned DiagDefaultParamID =
535 diag::err_param_default_argument_redefinition;
550 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
568 for (
auto Older = PrevForDefaultArgs;
570 Older = Older->getPreviousDecl();
571 OldParam = Older->getParamDecl(p);
576 }
else if (OldParamHasDfl) {
594 }
else if (NewParamHasDfl) {
598 diag::err_param_default_argument_template_redecl)
601 diag::note_template_prev_declaration)
632 if (Record->getDescribedClassTemplate())
634 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
641 diag::err_param_default_argument_member_template_redecl)
651 if (isa<CXXConstructorDecl>(New) &&
655 if (NewSM != OldSM) {
658 Diag(NewParam->
getLocation(), diag::err_default_arg_makes_ctor_special)
693 if (isa<CXXDeductionGuideDecl>(New) &&
705 Diag(New->
getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
739 if (!TemplateParamLists.empty()) {
742 Diag(TemplateParamLists.front()->getTemplateLoc(),
743 diag::err_decomp_decl_template);
749 ? diag::ext_decomp_decl
751 ? diag::ext_decomp_decl_cond
752 : diag::warn_cxx14_compat_decomp_decl)
775 if (
auto SCS = DS.getStorageClassSpec()) {
778 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
781 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
784 if (
auto TSCS = DS.getThreadStorageClassSpec()) {
786 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
788 if (DS.hasConstexprSpecifier()) {
789 BadSpecifiers.push_back(
791 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
793 if (DS.isInlineSpecified()) {
794 BadSpecifiers.push_back(
"inline");
795 BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
798 if (!BadSpecifiers.empty()) {
799 auto &&Err =
Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
800 Err << (
int)BadSpecifiers.size()
801 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(),
" ");
804 for (
auto Loc : BadSpecifierLocs)
806 }
else if (!CPlusPlus20Specifiers.empty()) {
807 auto &&Warn =
Diag(CPlusPlus20SpecifierLocs.front(),
809 ? diag::warn_cxx17_compat_decomp_decl_spec
810 : diag::ext_decomp_decl_spec);
811 Warn << (
int)CPlusPlus20Specifiers.size()
812 << llvm::join(CPlusPlus20Specifiers.begin(),
813 CPlusPlus20Specifiers.end(),
" ");
814 for (
auto Loc : CPlusPlus20SpecifierLocs)
826 Diag(DS.getVolatileSpecLoc(),
827 diag::warn_deprecated_volatile_structured_binding);
847 ? diag::err_decomp_decl_parens
848 : diag::err_decomp_decl_type)
859 if (DS.isConstrainedAuto()) {
862 "No other template kind should be possible for a constrained auto");
886 Previous.getFoundDecl()->isTemplateParameter()) {
905 auto *Old =
Previous.getRepresentativeDecl();
906 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
907 Diag(Old->getLocation(), diag::note_previous_definition);
924 bool AddToScope =
true;
944 S.
Diag(Src->
getLocation(), diag::err_decomp_decl_wrong_number_bindings)
957 E = GetInit(Loc, E.
get(), I++);
960 B->setBinding(ElemType, E.
get());
972 S,
Bindings, Src, DecompType, NumElems, ElemType,
1003 S,
Bindings, Src, DecompType, llvm::APSInt::get(2),
1007 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
1015 llvm::raw_svector_ostream OS(SS);
1034 auto DiagnoseMissing = [&] {
1044 return DiagnoseMissing();
1054 return DiagnoseMissing();
1055 if (Result.isAmbiguous())
1060 Result.suppressDiagnostics();
1062 S.
Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1074 Loc, TraitTy, DiagID,
1081 assert(RD &&
"specialization of class template is not a class?");
1100 namespace {
enum class IsTupleLike { TupleLike, NotTupleLike,
Error }; }
1118 return IsTupleLike::NotTupleLike;
1127 : R(R), Args(Args) {}
1130 return S.
Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1134 } Diagnoser(R, Args);
1145 return IsTupleLike::TupleLike;
1160 S, R, Loc,
"tuple_element", Args,
1161 diag::err_decomp_decl_std_tuple_element_not_specialized))
1167 S.
Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1179 struct InitializingBinding {
1188 ~InitializingBinding() {
1199 S.
Diag(Src->
getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1215 bool UseMemberGet =
false;
1225 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1227 if (TPL->
size() != 0 &&
1228 isa<NonTypeTemplateParmDecl>(TPL->
getParam(0))) {
1230 UseMemberGet =
true;
1239 InitializingBinding InitContext(S, B);
1262 MemberGet, &Args,
nullptr);
1296 B->getDeclName().getAsIdentifierInfo(), RefType,
1300 RefVD->setImplicit();
1302 RefVD->setInlineSpecified();
1303 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1314 RefVD->setInit(E.
get());
1323 B->setBinding(T, E.
get());
1338 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1347 ClassWithFields = RD;
1359 for (
auto &
P : Paths) {
1363 BestPath->back().Base->getType())) {
1365 S.
Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1366 <<
false << RD << BestPath->back().Base->getType()
1367 <<
P.back().Base->getType();
1369 }
else if (
P.Access < BestPath->
Access) {
1375 QualType BaseType = BestPath->back().Base->getType();
1377 S.
Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1384 *BestPath, diag::err_decomp_decl_inaccessible_base);
1395 S.
Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1396 << (ClassWithFields == RD) << RD << ClassWithFields
1397 << Paths.front().back().Base->getType();
1408 diag::err_incomplete_type))
1420 auto DiagnoseBadNumberOfBindings = [&]() ->
bool {
1421 unsigned NumFields = llvm::count_if(
1422 RD->
fields(), [](
FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1423 assert(
Bindings.size() != NumFields);
1424 S.
Diag(Src->
getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1434 for (
auto *FD : RD->
fields()) {
1435 if (FD->isUnnamedBitfield())
1440 if (!FD->getDeclName()) {
1447 if (FD->isAnonymousStructOrUnion()) {
1450 S.
Diag(FD->getLocation(), diag::note_declared_at);
1459 return DiagnoseBadNumberOfBindings();
1470 BasePair.
getAccess(), FD->getAccess())));
1493 if (FD->isMutable())
1499 return DiagnoseBadNumberOfBindings();
1547 case IsTupleLike::TupleLike:
1552 case IsTupleLike::NotTupleLike:
1561 << DD << !RD << DecompType;
1584 "Should only be called if types are otherwise the same.");
1595 NewType =
P->getPointeeType();
1628 if (FTD->isMemberSpecialization())
1652 diag::err_param_default_argument_missing_name)
1656 diag::err_param_default_argument_missing);
1664 template <
typename... Ts>
1674 std::forward<Ts>(DiagArgs)...);
1680 llvm_unreachable(
"unknown CheckConstexprKind");
1689 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1697 SemaRef.
Diag(Loc, diag::note_constexpr_dtor_subobject)
1705 if (!Check(B.getBaseTypeLoc(), B.getType(),
nullptr))
1708 if (!Check(FD->getLocation(), FD->getType(), FD))
1718 unsigned ArgIndex = 0;
1721 e = FT->param_type_end();
1722 i != e; ++i, ++ArgIndex) {
1726 diag::err_constexpr_non_literal_param, ArgIndex + 1,
1739 diag::err_constexpr_non_literal_return,
1755 default: llvm_unreachable(
"Invalid tag kind for record diagnostic!");
1786 << isa<CXXConstructorDecl>(NewFD)
1788 for (
const auto &I : RD->
vbases())
1789 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1790 << I.getSourceRange();
1795 if (!isa<CXXConstructorDecl>(NewFD)) {
1800 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1804 Diag(Method->
getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1817 if (WrittenVirtual != Method)
1819 diag::note_overridden_virtual_function);
1829 if (
auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1833 if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1847 "CheckConstexprFunctionDefinition called on function with no body");
1862 for (
const auto *DclIt : DS->
decls()) {
1863 switch (DclIt->getKind()) {
1864 case Decl::StaticAssert:
1866 case Decl::UsingShadow:
1867 case Decl::UsingDirective:
1868 case Decl::UnresolvedUsingTypename:
1869 case Decl::UnresolvedUsingValue:
1870 case Decl::UsingEnum:
1878 case Decl::TypeAlias: {
1881 const auto *TN = cast<TypedefNameDecl>(DclIt);
1882 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1885 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1888 << isa<CXXConstructorDecl>(Dcl);
1896 case Decl::CXXRecord:
1898 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1902 ? diag::warn_cxx11_compat_constexpr_type_definition
1903 : diag::ext_constexpr_type_definition)
1904 << isa<CXXConstructorDecl>(Dcl);
1911 case Decl::EnumConstant:
1912 case Decl::IndirectField:
1919 case Decl::Decomposition: {
1924 const auto *VD = cast<VarDecl>(DclIt);
1925 if (VD->isThisDeclarationADefinition()) {
1926 if (VD->isStaticLocal()) {
1928 SemaRef.
Diag(VD->getLocation(),
1930 ? diag::warn_cxx20_compat_constexpr_var
1931 : diag::ext_constexpr_static_var)
1932 << isa<CXXConstructorDecl>(Dcl)
1938 if (SemaRef.
LangOpts.CPlusPlus2b) {
1940 diag::warn_cxx20_compat_constexpr_var,
1941 isa<CXXConstructorDecl>(Dcl),
1944 SemaRef,
Kind, VD->getLocation(), VD->getType(),
1945 diag::err_constexpr_local_var_non_literal_type,
1946 isa<CXXConstructorDecl>(Dcl))) {
1949 if (!VD->getType()->isDependentType() &&
1950 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1955 ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1956 : diag::ext_constexpr_local_var_no_init)
1957 << isa<CXXConstructorDecl>(Dcl);
1965 SemaRef.
Diag(VD->getLocation(),
1967 ? diag::warn_cxx11_compat_constexpr_local_var
1968 : diag::ext_constexpr_local_var)
1969 << isa<CXXConstructorDecl>(Dcl);
1976 case Decl::NamespaceAlias:
1977 case Decl::Function:
1986 SemaRef.
Diag(DS->
getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1987 << isa<CXXConstructorDecl>(Dcl) << Dcl->
isConsteval();
2012 llvm::SmallSet<Decl*, 16> &Inits,
2020 if (Field->isInvalidDecl())
2023 if (Field->isUnnamedBitfield())
2029 if (Field->isAnonymousStructOrUnion() &&
2030 (Field->getType()->isUnionType()
2031 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2032 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
2035 if (!Inits.count(Field)) {
2040 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
2041 : diag::ext_constexpr_ctor_missing_init);
2044 SemaRef.
Diag(Field->getLocation(),
2045 diag::note_constexpr_ctor_missing_init);
2049 }
else if (Field->isAnonymousStructOrUnion()) {
2051 for (
auto *I : RD->
fields())
2054 if (!RD->
isUnion() || Inits.count(I))
2071 switch (S->getStmtClass()) {
2072 case Stmt::NullStmtClass:
2076 case Stmt::DeclStmtClass:
2086 case Stmt::ReturnStmtClass:
2088 if (isa<CXXConstructorDecl>(Dcl)) {
2091 Cxx1yLoc = S->getBeginLoc();
2095 ReturnStmts.push_back(S->getBeginLoc());
2098 case Stmt::AttributedStmtClass:
2102 SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts,
2103 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc,
Kind);
2105 case Stmt::CompoundStmtClass: {
2108 Cxx1yLoc = S->getBeginLoc();
2111 for (
auto *BodyIt : CompStmt->
body()) {
2113 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc,
Kind))
2119 case Stmt::IfStmtClass: {
2122 Cxx1yLoc = S->getBeginLoc();
2124 IfStmt *If = cast<IfStmt>(S);
2126 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc,
Kind))
2130 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc,
Kind))
2135 case Stmt::WhileStmtClass:
2136 case Stmt::DoStmtClass:
2137 case Stmt::ForStmtClass:
2138 case Stmt::CXXForRangeStmtClass:
2139 case Stmt::ContinueStmtClass:
2145 Cxx1yLoc = S->getBeginLoc();
2146 for (
Stmt *SubStmt : S->children()) {
2149 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc,
Kind))
2154 case Stmt::SwitchStmtClass:
2155 case Stmt::CaseStmtClass:
2156 case Stmt::DefaultStmtClass:
2157 case Stmt::BreakStmtClass:
2161 Cxx1yLoc = S->getBeginLoc();
2162 for (
Stmt *SubStmt : S->children()) {
2165 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc,
Kind))
2170 case Stmt::LabelStmtClass:
2171 case Stmt::GotoStmtClass:
2173 Cxx2bLoc = S->getBeginLoc();
2174 for (
Stmt *SubStmt : S->children()) {
2177 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc,
Kind))
2182 case Stmt::GCCAsmStmtClass:
2183 case Stmt::MSAsmStmtClass:
2185 case Stmt::CXXTryStmtClass:
2187 Cxx2aLoc = S->getBeginLoc();
2188 for (
Stmt *SubStmt : S->children()) {
2191 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc,
Kind))
2196 case Stmt::CXXCatchStmtClass:
2200 SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,
2201 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc,
Kind))
2211 Cxx1yLoc = S->getBeginLoc();
2216 SemaRef.
Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2217 << isa<CXXConstructorDecl>(Dcl) << Dcl->
isConsteval();
2232 if (isa<CXXTryStmt>(Body)) {
2254 ? diag::ext_constexpr_function_try_block_cxx20
2255 : diag::warn_cxx17_compat_constexpr_function_try_block)
2256 << isa<CXXConstructorDecl>(Dcl);
2270 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc,
Kind))
2281 }
else if (Cxx2bLoc.
isValid()) {
2282 SemaRef.
Diag(Cxx2bLoc,
2284 ? diag::warn_cxx20_compat_constexpr_body_invalid_stmt
2285 : diag::ext_constexpr_body_invalid_stmt_cxx2b)
2286 << isa<CXXConstructorDecl>(Dcl);
2287 }
else if (Cxx2aLoc.
isValid()) {
2288 SemaRef.
Diag(Cxx2aLoc,
2290 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2291 : diag::ext_constexpr_body_invalid_stmt_cxx20)
2292 << isa<CXXConstructorDecl>(Dcl);
2293 }
else if (Cxx1yLoc.
isValid()) {
2294 SemaRef.
Diag(Cxx1yLoc,
2296 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2297 : diag::ext_constexpr_body_invalid_stmt)
2298 << isa<CXXConstructorDecl>(Dcl);
2302 = dyn_cast<CXXConstructorDecl>(Dcl)) {
2311 if (Constructor->getNumCtorInitializers() == 0 &&
2317 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2318 : diag::ext_constexpr_union_ctor_no_init);
2323 }
else if (!Constructor->isDependentContext() &&
2324 !Constructor->isDelegatingConstructor()) {
2325 assert(RD->
getNumVBases() == 0 &&
"constexpr ctor with virtual bases");
2329 bool AnyAnonStructUnionMembers =
false;
2330 unsigned Fields = 0;
2332 E = RD->
field_end(); I != E; ++I, ++Fields) {
2333 if (I->isAnonymousStructOrUnion()) {
2334 AnyAnonStructUnionMembers =
true;
2342 if (AnyAnonStructUnionMembers ||
2343 Constructor->getNumCtorInitializers() != RD->
getNumBases() + Fields) {
2347 llvm::SmallSet<Decl*, 16> Inits;
2348 for (
const auto *I: Constructor->inits()) {
2352 Inits.insert(
ID->chain_begin(),
ID->chain_end());
2355 bool Diagnosed =
false;
2356 for (
auto *I : RD->
fields())
2363 if (ReturnStmts.empty()) {
2374 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2375 : diag::err_constexpr_body_no_return)
2389 }
else if (ReturnStmts.size() > 1) {
2395 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2396 : diag::ext_constexpr_body_multiple_return);
2397 for (
unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2398 SemaRef.
Diag(ReturnStmts[I],
2399 diag::note_constexpr_body_previous_return);
2427 diag::ext_constexpr_function_never_constant_expr)
2428 << isa<CXXConstructorDecl>(Dcl) << Dcl->
isConsteval();
2429 for (
size_t I = 0, N =
Diags.size(); I != N; ++I)
2454 return dyn_cast_or_null<CXXRecordDecl>(DC);
2457 return dyn_cast_or_null<CXXRecordDecl>(
CurContext);
2482 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2484 CurDecl = dyn_cast_or_null<CXXRecordDecl>(
CurContext);
2502 Class = Class->getCanonicalDecl();
2504 for (
const auto &I : Current->bases()) {
2513 if (
Base->getCanonicalDecl() == Class)
2516 Queue.push_back(
Base);
2522 Current = Queue.pop_back_val();
2550 if (Class->isUnion()) {
2551 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2558 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2570 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2571 ((BaseDecl = BaseDecl->getDefinition()) &&
2573 Diag(BaseLoc, diag::err_circular_inheritance)
2576 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2577 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2590 if (!Class->getTypeForDecl()->isDependentType())
2591 Class->setInvalidDecl();
2594 Access, TInfo, EllipsisLoc);
2599 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2606 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2613 if (
auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2625 diag::err_incomplete_base_class, SpecifierRange)) {
2626 Class->setInvalidDecl();
2632 assert(BaseDecl &&
"Record type has no declaration");
2634 assert(BaseDecl &&
"Base type is not incomplete, but has no definition");
2636 assert(CXXBaseDecl &&
"Base type is not a C++ type");
2641 const auto *BaseCSA = CXXBaseDecl->
getAttr<CodeSegAttr>();
2642 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2643 if ((DerivedCSA || BaseCSA) &&
2644 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2645 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2646 Diag(CXXBaseDecl->
getLocation(), diag::note_base_class_specified_here)
2658 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2666 if (FinalAttr *FA = CXXBaseDecl->
getAttr<FinalAttr>()) {
2667 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2669 << FA->isSpelledAsSealed();
2676 Class->setInvalidDecl();
2681 Access, TInfo, EllipsisLoc);
2703 Class->setIsParsingBaseSpecifiers();
2711 ? (
unsigned)diag::warn_unknown_attribute_ignored
2712 : (
unsigned)diag::err_base_specifier_attribute)
2713 << AL << AL.getRange();
2729 Class->setInvalidDecl();
2746 auto Decl = Rec->getAsCXXRecordDecl();
2749 for (
const auto &BaseSpec :
Decl->bases()) {
2752 if (Set.insert(
Base).second)
2770 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2777 unsigned NumGoodBases = 0;
2778 bool Invalid =
false;
2779 for (
unsigned idx = 0; idx < Bases.size(); ++idx) {
2789 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2790 << KnownBase->
getType() << Bases[idx]->getSourceRange();
2799 KnownBase = Bases[idx];
2800 Bases[NumGoodBases++] = Bases[idx];
2805 if (Bases.size() > 1)
2809 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2810 if (Class->isInterface() &&
2821 Class->addAttr(WeakAttr::CreateImplicit(
Context));
2827 Class->setBases(Bases.data(), NumGoodBases);
2830 for (
unsigned idx = 0; idx < NumGoodBases; ++idx) {
2832 QualType BaseType = Bases[idx]->getType();
2842 if (IndirectBaseTypes.count(CanonicalBase)) {
2846 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2850 if (Paths.isAmbiguous(CanonicalBase))
2851 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2853 << Bases[idx]->getSourceRange();
2855 assert(Bases[idx]->isVirtual());
2871 if (!ClassDecl || Bases.empty())
2932 for (
unsigned I = Path.size(); I != 0; --I) {
2933 if (Path[I - 1].
Base->isVirtual()) {
2940 for (
unsigned I = Start, E = Path.size(); I != E; ++I)
2947 assert(BasePathArray.empty() &&
"Base path array must be empty!");
2948 assert(Paths.isRecordingPaths() &&
"Must record paths!");
2965 unsigned InaccessibleBaseID,
2966 unsigned AmbiguousBaseConvID,
2970 bool IgnoreAccess) {
2978 if (!DerivationOkay)
2983 Path = &Paths.front();
2990 if (PossiblePath.size() == 1) {
2991 Path = &PossiblePath;
2992 if (AmbiguousBaseConvID)
2993 Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2994 <<
Base << Derived << Range;
3001 if (!IgnoreAccess) {
3020 if (AmbiguousBaseConvID) {
3028 Paths.setRecordingPaths(
true);
3030 assert(StillOkay &&
"Can only be used with a derived-to-base conversion");
3039 Diag(Loc, AmbiguousBaseConvID)
3040 << Derived <<
Base << PathDisplayStr << Range << Name;
3049 bool IgnoreAccess) {
3051 Derived,
Base, diag::err_upcast_to_inaccessible_base,
3052 diag::err_ambiguous_derived_to_base_conv, Loc, Range,
DeclarationName(),
3053 BasePath, IgnoreAccess);
3071 std::set<unsigned> DisplayedPaths;
3073 Path != Paths.end(); ++Path) {
3074 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
3077 PathDisplayStr +=
"\n ";
3079 for (CXXBasePath::const_iterator Element = Path->begin();
3080 Element != Path->end(); ++Element)
3081 PathDisplayStr +=
" -> " + Element->Base->getType().getAsString();
3085 return PathDisplayStr;
3096 assert(Access !=
AS_none &&
"Invalid kind for syntactic access specifier!");
3126 if (!OverloadedMethods.empty()) {
3127 if (OverrideAttr *OA = D->
getAttr<OverrideAttr>()) {
3128 Diag(OA->getLocation(),
3129 diag::override_keyword_hides_virtual_member_function)
3130 <<
"override" << (OverloadedMethods.size() > 1);
3131 }
else if (FinalAttr *FA = D->
getAttr<FinalAttr>()) {
3132 Diag(FA->getLocation(),
3133 diag::override_keyword_hides_virtual_member_function)
3134 << (FA->isSpelledAsSealed() ?
"sealed" :
"final")
3135 << (OverloadedMethods.size() > 1);
3146 if (OverrideAttr *OA = D->
getAttr<OverrideAttr>()) {
3147 Diag(OA->getLocation(),
3148 diag::override_keyword_only_allowed_on_virtual_member_functions)
3152 if (FinalAttr *FA = D->
getAttr<FinalAttr>()) {
3153 Diag(FA->getLocation(),
3154 diag::override_keyword_only_allowed_on_virtual_member_functions)
3155 << (FA->isSpelledAsSealed() ?
"sealed" :
"final")
3167 if (MD->
hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3168 Diag(MD->
getLocation(), diag::err_function_marked_override_not_overriding)
3188 auto EmitDiag = [&](
unsigned DiagInconsistent,
unsigned DiagSuggest) {
3197 if (isa<CXXDestructorDecl>(MD))
3199 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3200 diag::warn_suggest_destructor_marked_not_override_overriding);
3202 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3203 diag::warn_suggest_function_marked_not_override_overriding);
3212 FinalAttr *FA = Old->
getAttr<FinalAttr>();
3218 << FA->isSpelledAsSealed();
3227 return !RD->isCompleteDefinition() ||
3228 !RD->hasTrivialDefaultConstructor() ||
3229 !RD->hasTrivialDestructor();
3235 llvm::find_if(list, [](
const ParsedAttr &AL) {
3238 if (Itr != list.
end())
3252 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3255 const auto Base =
Specifier->getType()->getAsCXXRecordDecl();
3257 if (Bases.find(
Base) != Bases.end())
3259 for (
const auto Field :
Base->lookup(FieldName)) {
3260 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3263 assert(Bases.find(
Base) == Bases.end());
3276 for (
const auto &
P : Paths) {
3277 auto Base =
P.back().Base->getType()->getAsCXXRecordDecl();
3278 auto It = Bases.find(
Base);
3280 if (It == Bases.end())
3282 auto BaseField = It->second;
3283 assert(BaseField->getAccess() !=
AS_private);
3286 Diag(Loc, diag::warn_shadow_field)
3287 << FieldName << RD <<
Base << DeclIsField;
3288 Diag(BaseField->getLocation(), diag::note_shadow_field);
3313 Expr *BitWidth =
static_cast<Expr*
>(BW);
3322 if (cast<CXXRecordDecl>(
CurContext)->isInterface()) {
3326 unsigned InvalidDecl;
3327 bool ShowDeclName =
true;
3337 else switch (Name.getNameKind()) {
3340 ShowDeclName =
false;
3345 ShowDeclName =
false;
3360 Diag(Loc, diag::err_invalid_member_in_interface)
3361 << (InvalidDecl-1) << Name;
3363 Diag(Loc, diag::err_invalid_member_in_interface)
3364 << (InvalidDecl-1) <<
"";
3390 diag::err_storageclass_invalid_for_member);
3410 const char *PrevSpec;
3415 assert(!Failed &&
"Making a constexpr member const shouldn't fail");
3419 const char *PrevSpec;
3425 "This is the only DeclSpec that should fail to be applied");
3429 isInstField =
false;
3439 if (!Name.isIdentifier()) {
3440 Diag(Loc, diag::err_bad_variable_name)
3449 if (TemplateParameterLists.size()) {
3451 if (TemplateParams->
size()) {
3460 diag::err_template_member_noparams)
3495 if (MSPropertyAttr) {
3497 BitWidth, InitStyle, AS, *MSPropertyAttr);
3500 isInstField =
false;
3503 BitWidth, InitStyle, AS);
3508 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(
CurContext));
3516 if (
Member->isInvalidDecl()) {
3518 }
else if (isa<VarDecl>(
Member) || isa<VarTemplateDecl>(
Member)) {
3521 Diag(Loc, diag::err_static_not_bitfield)
3523 }
else if (isa<TypedefDecl>(
Member)) {
3525 Diag(Loc, diag::err_typedef_not_bitfield)
3530 Diag(Loc, diag::err_not_integral_type_bitfield)
3531 << Name << cast<ValueDecl>(
Member)->getType()
3536 Member->setInvalidDecl();
3541 NonTemplateMember = FunTmpl->getTemplatedDecl();
3543 NonTemplateMember = VarTmpl->getTemplatedDecl();
3549 if (NonTemplateMember !=
Member)
3555 if (
auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3556 auto *TD = DG->getDeducedTemplate();
3559 if (AS != TD->getAccess() &&
3560 TD->getDeclContext()->getRedeclContext()->Equals(
3561 DG->getDeclContext()->getRedeclContext())) {
3562 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3563 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3566 for (
const auto *D : cast<CXXRecordDecl>(
CurContext)->decls()) {
3567 if (
const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3568 LastAccessSpec = AccessSpec;
3570 assert(LastAccessSpec &&
"differing access with no access specifier");
3571 Diag(LastAccessSpec->
getBeginLoc(), diag::note_deduction_guide_access)
3581 Member->addAttr(FinalAttr::Create(
3593 assert((Name || isInstField) &&
"No identifier for non-field ?");
3615 class UninitializedFieldVisitor
3620 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3623 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3638 UninitializedFieldVisitor(
Sema &S,
3639 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3640 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3641 : Inherited(S.
Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3642 Constructor(nullptr), InitList(
false), InitListFieldDecl(nullptr) {}
3645 bool IsInitListMemberExprInitialized(
MemberExpr *ME,
3646 bool CheckReferenceOnly) {
3648 bool ReferenceField =
false;
3653 Fields.push_back(FD);
3655 ReferenceField =
true;
3661 if (CheckReferenceOnly && !ReferenceField)
3667 for (
const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields)))
3670 for (
auto UsedIter = UsedFieldIndex.begin(),
3671 UsedEnd = UsedFieldIndex.end(),
3672 OrigIter = InitFieldIndex.begin(),
3673 OrigEnd = InitFieldIndex.end();
3674 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3675 if (*UsedIter < *OrigIter)
3677 if (*UsedIter > *OrigIter)
3684 void HandleMemberExpr(
MemberExpr *ME,
bool CheckReferenceOnly,
3697 dyn_cast<MemberExpr>(
Base->IgnoreParenImpCasts())) {
3699 if (isa<VarDecl>(SubME->getMemberDecl()))
3702 if (
FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3707 AllPODFields =
false;
3709 Base = SubME->getBase();
3712 if (!isa<CXXThisExpr>(
Base->IgnoreParenImpCasts())) {
3717 if (AddressOf && AllPODFields)
3723 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3724 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3727 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3737 if (!Decls.count(FoundVD))
3742 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3744 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3749 if (CheckReferenceOnly && !IsReference)
3753 unsigned diag = IsReference
3754 ? diag::warn_reference_field_is_uninit
3755 : diag::warn_field_is_uninit;
3759 diag::note_uninit_in_this_constructor)
3764 void HandleValue(
Expr *E,
bool AddressOf) {
3767 if (
MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3768 HandleMemberExpr(ME,
false ,
3774 Visit(CO->getCond());
3775 HandleValue(CO->getTrueExpr(), AddressOf);
3776 HandleValue(CO->getFalseExpr(), AddressOf);
3781 dyn_cast<BinaryConditionalOperator>(E)) {
3782 Visit(BCO->getCond());
3783 HandleValue(BCO->getFalseExpr(), AddressOf);
3788 HandleValue(OVE->getSourceExpr(), AddressOf);
3793 switch (BO->getOpcode()) {
3798 HandleValue(BO->getLHS(), AddressOf);
3799 Visit(BO->getRHS());
3802 Visit(BO->getLHS());
3803 HandleValue(BO->getRHS(), AddressOf);
3812 InitFieldIndex.push_back(0);
3813 for (
auto *Child : ILE->
children()) {
3814 if (
InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3815 CheckInitListExpr(SubList);
3819 ++InitFieldIndex.back();
3821 InitFieldIndex.pop_back();
3830 DeclsToRemove.clear();
3837 InitListFieldDecl =
Field;
3838 InitFieldIndex.clear();
3839 CheckInitListExpr(ILE);
3853 HandleMemberExpr(ME,
true ,
false );
3862 Inherited::VisitImplicitCastExpr(E);
3868 if (
InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3872 if (ICE->getCastKind() == CK_NoOp)
3873 ArgExpr = ICE->getSubExpr();
3874 HandleValue(ArgExpr,
false );
3877 Inherited::VisitCXXConstructExpr(E);
3882 if (isa<MemberExpr>(Callee)) {
3883 HandleValue(Callee,
false );
3889 Inherited::VisitCXXMemberCallExpr(E);
3895 HandleValue(E->
getArg(0),
false);
3899 Inherited::VisitCallExpr(E);
3905 if (isa<UnresolvedLookupExpr>(Callee))
3906 return Inherited::VisitCXXOperatorCallExpr(E);
3910 HandleValue(Arg->IgnoreParenImpCasts(),
false );
3920 DeclsToRemove.push_back(FD);
3923 HandleValue(E->
getLHS(),
false );
3928 Inherited::VisitBinaryOperator(E);
3938 HandleValue(ME->
getBase(),
true );
3943 Inherited::VisitUnaryOperator(E);
3953 static void DiagnoseUninitializedFields(
3973 for (
auto *I : RD->
decls()) {
3974 if (
auto *FD = dyn_cast<FieldDecl>(I)) {
3975 UninitializedFields.insert(FD);
3976 }
else if (
auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3977 UninitializedFields.insert(IFD->getAnonField());
3982 for (
auto I : RD->
bases())
3983 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3985 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3988 UninitializedFieldVisitor UninitializedChecker(SemaRef,
3989 UninitializedFields,
3990 UninitializedBaseClasses);
3992 for (
const auto *FieldInit :
Constructor->inits()) {
3993 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3996 Expr *InitExpr = FieldInit->getInit();
4001 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
4002 InitExpr =
Default->getExpr();
4006 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
4007 FieldInit->getAnyMember(),
4008 FieldInit->getBaseClass());
4010 UninitializedChecker.CheckInitializer(InitExpr,
nullptr,
4011 FieldInit->getAnyMember(),
4012 FieldInit->getBaseClass());
4035 auto *ParamDecl = cast<NamedDecl>(Param.Param);
4036 if (ParamDecl->getDeclName())
4057 return ConstraintExpr;
4072 return Seq.
Perform(*
this, Entity,
Kind, InitExpr);
4086 "must set init style when field is created");
4103 assert(Init.isUsable() &&
"Init should at least have a RecoveryExpr");
4109 if (!Init.isInvalid())
4111 if (Init.isInvalid()) {
4129 DirectBaseSpec =
nullptr;
4130 for (
const auto &
Base : ClassDecl->
bases()) {
4134 DirectBaseSpec = &
Base;
4142 VirtualBaseSpec =
nullptr;
4143 if (!DirectBaseSpec || !DirectBaseSpec->
isVirtual()) {
4152 Path != Paths.end(); ++Path) {
4153 if (Path->back().Base->isVirtual()) {
4154 VirtualBaseSpec = Path->back().Base;
4161 return DirectBaseSpec || VirtualBaseSpec;
4176 DS, IdLoc, InitList,
4195 DS, IdLoc, List, EllipsisLoc);
4204 explicit MemInitializerValidatorCCC(
CXXRecordDecl *ClassDecl)
4205 : ClassDecl(ClassDecl) {}
4207 bool ValidateCandidate(
const TypoCorrection &candidate)
override {
4209 if (
FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4210 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4211 return isa<TypeDecl>(ND);
4216 std::unique_ptr<CorrectionCandidateCallback> clone()
override {
4217 return std::make_unique<MemInitializerValidatorCCC>(*
this);
4232 for (
auto *D : ClassDecl->
lookup(MemberOrBase))
4233 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
4234 return cast<ValueDecl>(D);
4261 = dyn_cast<CXXConstructorDecl>(ConstructorD);
4285 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4287 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4289 <<
SourceRange(IdLoc, Init->getSourceRange().getEnd());
4297 if (TemplateTypeTy) {
4318 bool NotUnknownSpecialization =
false;
4320 if (
CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4321 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4323 if (!NotUnknownSpecialization) {
4328 *MemberOrBase, IdLoc);
4348 auto *TempSpec = cast<TemplateSpecializationType>(
4349 UnqualifiedBase->getInjectedClassNameSpecialization());
4351 for (
auto const &
Base : ClassDecl->
bases()) {
4355 BaseTemplate->getTemplateName(), TN)) {
4356 Diag(IdLoc, diag::ext_unqualified_base_class)
4357 <<
SourceRange(IdLoc, Init->getSourceRange().getEnd());
4358 BaseType =
Base.getType();
4367 MemInitializerValidatorCCC CCC(ClassDecl);
4376 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4377 << MemberOrBase <<
true);
4384 DirectBaseSpec, VirtualBaseSpec)) {
4389 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4390 << MemberOrBase <<
false,
4403 if (!TyD && BaseType.
isNull()) {
4404 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4405 << MemberOrBase <<
SourceRange(IdLoc,Init->getSourceRange().getEnd());
4432 assert((DirectMember || IndirectMember) &&
4433 "Member must be a FieldDecl or IndirectFieldDecl");
4438 if (
Member->isInvalidDecl())
4442 if (
ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4443 Args =
MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4444 }
else if (
InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4445 Args =
MultiExprArg(InitList->getInits(), InitList->getNumInits());
4453 if (
Member->getType()->isDependentType() || Init->isTypeDependent()) {
4458 bool InitList =
false;
4459 if (isa<InitListExpr>(Init)) {
4471 IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4495 Init = MemberInit.
get();
4515 return Diag(NameLoc, diag::err_delegating_ctor)
4517 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4519 bool InitList =
true;
4521 if (
ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4523 Args =
MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4532 NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4540 cast<CXXConstructExpr>(DelegationInit.
get())->getConstructor()) &&
4541 "Delegating constructor with no target?");
4547 DelegationInit.
get(), InitRange.
getBegin(),
false);
4565 DelegationInit = Init;
4580 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4600 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4629 if (!DirectBaseSpec && !VirtualBaseSpec) {
4638 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4650 InitRange.
getEnd(), EllipsisLoc);
4657 if (DirectBaseSpec && VirtualBaseSpec)
4658 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4663 BaseSpec = VirtualBaseSpec;
4666 bool InitList =
true;
4668 if (
ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4670 Args =
MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4710 InitRange.
getEnd(), EllipsisLoc);
4720 TargetType, ExprLoc);
4740 bool IsInheritedVirtualBase,
4744 IsInheritedVirtualBase);
4748 switch (ImplicitInitKind) {
4754 BaseInit = InitSeq.
Perform(SemaRef, InitEntity, InitKind, std::nullopt);
4760 bool Moving = ImplicitInitKind ==
IIK_Move;
4761 ParmVarDecl *Param = Constructor->getParamDecl(0);
4767 Constructor->getLocation(), ParamType,
4782 BasePath.push_back(BaseSpec);
4784 CK_UncheckedDerivedToBase,
4792 BaseInit = InitSeq.
Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4815 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4824 if (Field->isInvalidDecl())
4830 bool Moving = ImplicitInitKind ==
IIK_Move;
4831 ParmVarDecl *Param = Constructor->getParamDecl(0);
4835 if (Field->isZeroLengthBitField(SemaRef.
Context))
4838 Expr *MemberExprBase =
4851 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4853 MemberLookup.
addDecl(Indirect ? cast<ValueDecl>(Indirect)
4889 InitSeq.Perform(SemaRef, Entity, InitKind,
MultiExprArg(&CtorArgE, 1));
4904 "Unhandled implicit init kind!");
4920 InitSeq.
Perform(SemaRef, InitEntity, InitKind, std::nullopt);
4940 if (!Field->getParent()->isUnion()) {
4942 SemaRef.
Diag(Constructor->getLocation(),
4943 diag::err_uninitialized_member_in_ctor)
4944 << (
int)Constructor->isImplicit()
4946 << 0 << Field->getDeclName();
4947 SemaRef.
Diag(Field->getLocation(), diag::note_declared_at);
4952 SemaRef.
Diag(Constructor->getLocation(),
4953 diag::err_uninitialized_member_in_ctor)
4954 << (
int)Constructor->isImplicit()
4956 << 1 << Field->getDeclName();
4957 SemaRef.
Diag(Field->getLocation(), diag::note_declared_at);
4974 CXXMemberInit =
nullptr;
4979 struct BaseAndFieldInfo {
4982 bool AnyErrorsInInits;
4984 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4986 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4989 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
5001 bool isImplicitCopyOrMove()
const {
5012 llvm_unreachable(
"Invalid ImplicitInitializerKind!");
5016 AllToInit.push_back(Init);
5019 if (Init->getInit()->HasSideEffects(S.
Context))
5025 bool isInactiveUnionMember(
FieldDecl *Field) {
5032 return Active !=
Field->getCanonicalDecl();
5035 if (isImplicitCopyOrMove())
5040 if (
Field->hasInClassInitializer())
5044 if (!
Field->isAnonymousStructOrUnion())
5053 bool isWithinInactiveUnionMember(
FieldDecl *Field,
5056 return isInactiveUnionMember(Field);
5058 for (
auto *C : Indirect->
chain()) {
5060 if (Field && isInactiveUnionMember(Field))
5075 if (!ArrayT->getSize())
5078 T = ArrayT->getElementType();
5087 if (Field->isInvalidDecl())
5092 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
5093 return Info.addFieldInitializer(Init);
5107 if (Info.isWithinInactiveUnionMember(Field, Indirect))
5110 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5128 return Info.addFieldInitializer(Init);
5138 if (Info.AnyErrorsInInits)
5149 return Info.addFieldInitializer(Init);
5156 Constructor->setNumCtorInitializers(1);
5160 Constructor->setCtorInitializers(initializer);
5169 DiagnoseUninitializedFields(*
this, Constructor);
5176 if (Constructor->isDependentContext()) {
5179 if (!Initializers.empty()) {
5180 Constructor->setNumCtorInitializers(Initializers.size());
5183 memcpy(baseOrMemberInitializers, Initializers.data(),
5185 Constructor->setCtorInitializers(baseOrMemberInitializers);
5190 Constructor->setInvalidDecl();
5195 BaseAndFieldInfo Info(*
this, Constructor, AnyErrors);
5199 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5203 bool HadError =
false;
5205 for (
unsigned i = 0; i < Initializers.size(); i++) {
5208 if (
Member->isBaseInitializer())
5211 Info.AllBaseFields[
Member->getAnyMember()->getCanonicalDecl()] =
Member;
5214 for (
auto *C : F->chain()) {
5217 Info.ActiveUnionMember.insert(std::make_pair(
5222 Info.ActiveUnionMember.insert(std::make_pair(
5230 for (
auto &I : ClassDecl->
bases()) {
5232 DirectVBases.insert(&I);
5236 for (
auto &VBase : ClassDecl->
vbases()) {
5238 = Info.AllBaseFields.lookup(VBase.getType()->getAs<
RecordType>())) {
5246 Diag(
Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5247 << VBase.getType() << ClassDecl;
5251 Info.AllToInit.push_back(
Value);
5252 }
else if (!AnyErrors && !ClassDecl->
isAbstract()) {
5257 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5260 &VBase, IsInheritedVirtualBase,
5266 Info.AllToInit.push_back(CXXBaseInit);
5273 if (
Base.isVirtual())
5277 = Info.AllBaseFields.lookup(
Base.getType()->getAs<
RecordType>())) {
5278 Info.AllToInit.push_back(
Value);
5279 }
else if (!AnyErrors) {
5288 Info.AllToInit.push_back(CXXBaseInit);
5293 for (
auto *Mem : ClassDecl->
decls()) {
5294 if (
auto *F = dyn_cast<FieldDecl>(Mem)) {
5299 if (F->isUnnamedBitfield())
5305 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5314 if (Info.isImplicitCopyOrMove())
5317 if (
auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5318 if (F->getType()->isIncompleteArrayType()) {
5320 "Incomplete array type is not valid");
5332 unsigned NumInitializers = Info.AllToInit.size();
5333 if (NumInitializers > 0) {
5334 Constructor->setNumCtorInitializers(NumInitializers);
5337 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5339 Constructor->setCtorInitializers(baseOrMemberInitializers);
5344 Constructor->getParent());
5354 for (
auto *Field : RD->
fields())
5359 IdealInits.push_back(Field->getCanonicalDecl());
5368 if (!
Member->isAnyMemberInitializer())
5371 return Member->getAnyMember()->getCanonicalDecl();
5377 if (
Previous->isAnyMemberInitializer())
5382 if (Current->isAnyMemberInitializer())
5383 Diag << 0 << Current->getAnyMember();
5385 Diag << 1 << Current->getTypeSourceInfo()->getType();
5391 if (Constructor->getDeclContext()->isDependentContext())
5396 bool ShouldCheckOrder =
false;
5397 for (
unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5399 if (!SemaRef.
Diags.
isIgnored(diag::warn_initializer_out_of_order,
5400 Init->getSourceLocation())) {
5401 ShouldCheckOrder =
true;
5405 if (!ShouldCheckOrder)
5416 for (
const auto &VBase : ClassDecl->
vbases())
5420 for (
const auto &
Base : ClassDecl->
bases()) {
5421 if (
Base.isVirtual())
5427 for (
auto *Field : ClassDecl->
fields()) {
5428 if (Field->isUnnamedBitfield())
5434 unsigned NumIdealInits = IdealInitKeys.size();
5435 unsigned IdealIndex = 0;
5444 for (
unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5449 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5450 if (InitKey == IdealInitKeys[IdealIndex])
5456 if (IdealIndex == NumIdealInits && InitIndex) {
5457 WarnIndexes.push_back(InitIndex);
5460 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5461 if (InitKey == IdealInitKeys[IdealIndex])
5464 assert(IdealIndex < NumIdealInits &&
5465 "initializer not found in initializer list");
5467 CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5470 if (WarnIndexes.empty())
5474 llvm::sort(CorrelatedInitOrder, llvm::less_first());
5480 Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5481 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5482 : diag::warn_some_initializers_out_of_order);
5484 for (
unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5485 if (CorrelatedInitOrder[I].second == I)
5500 if (WarnIndexes.size() == 1) {
5502 Inits[WarnIndexes.front()]);
5508 for (
unsigned WarnIndex : WarnIndexes) {
5511 diag::note_initializer_out_of_order);
5518 bool CheckRedundantInit(
Sema &S,
5526 if (
FieldDecl *Field = Init->getAnyMember())
5527 S.
Diag(Init->getSourceLocation(),
5528 diag::err_multiple_mem_initialization)
5529 <<
Field->getDeclName()
5530 << Init->getSourceRange();
5532 const Type *BaseClass = Init->getBaseClass();
5533 assert(BaseClass &&
"neither field nor base");
5534 S.
Diag(Init->getSourceLocation(),
5535 diag::err_multiple_base_initialization)
5537 << Init->getSourceRange();
5545 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5546 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5548 bool CheckRedundantUnionInit(
Sema &S,
5550 RedundantUnionMap &Unions) {
5555 while (
Parent->isAnonymousStructOrUnion() ||
Parent->isUnion()) {
5557 UnionEntry &En = Unions[
Parent];
5558 if (En.first && En.first != Child) {
5559 S.
Diag(Init->getSourceLocation(),
5560 diag::err_multiple_mem_union_initialization)
5561 <<
Field->getDeclName()
5562 << Init->getSourceRange();
5563 S.
Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5564 << 0 << En.second->getSourceRange();
5571 if (!
Parent->isAnonymousStructOrUnion())
5588 if (!ConstructorDecl)
5594 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5597 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5604 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5607 RedundantUnionMap MemberUnions;
5609 bool HadError =
false;
5610 for (
unsigned i = 0; i < MemInits.size(); i++) {
5614 Init->setSourceOrder(i);
5616 if (Init->isAnyMemberInitializer()) {
5618 if (CheckRedundantInit(*
this, Init, Members[Key]) ||
5619 CheckRedundantUnionInit(*
this, Init, MemberUnions))
5621 }
else if (Init->isBaseInitializer()) {
5623 if (CheckRedundantInit(*
this, Init, Members[Key]))
5626 assert(Init->isDelegatingInitializer());
5628 if (MemInits.size() != 1) {
5629 Diag(Init->getSourceLocation(),
5630 diag::err_delegating_initializer_alone)
5631 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5647 DiagnoseUninitializedFields(*
this, Constructor);
5664 for (
auto *Field : ClassDecl->
fields()) {
5665 if (Field->isInvalidDecl())
5692 PDiag(diag::err_access_dtor_field)
5693 << Field->getDeclName()
5702 bool VisitVirtualBases = !ClassDecl->
isAbstract();
5709 if (Dtor && Dtor->
isUsed())
5710 VisitVirtualBases =
false;
5716 for (
const auto &
Base : ClassDecl->
bases()) {
5722 if (
Base.isVirtual()) {
5723 if (!VisitVirtualBases)
5725 DirectVirtualBases.insert(RT);
5742 PDiag(diag::err_access_dtor_base)
5743 <<
Base.getType() <<
Base.getSourceRange(),
5750 if (VisitVirtualBases)
5752 &DirectVirtualBases);
5757 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5759 for (
const auto &VBase : ClassDecl->
vbases()) {
5764 if (DirectVirtualBases && DirectVirtualBases->count(RT))
5780 PDiag(diag::err_access_dtor_vbase)
5786 diag::err_access_dtor_vbase, 0, ClassDecl->
getLocation(),
5800 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5802 DiagnoseUninitializedFields(*
this, Constructor);
5857 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5858 MEnd = FinalOverriders.end();
5862 SOEnd = M->second.end();
5863 SO != SOEnd; ++SO) {
5870 if (SO->second.size() != 1)
5873 if (!SO->second.front().Method->isPure())
5876 if (!SeenPureMethods.insert(SO->second.front().Method).second)
5879 Diag(SO->second.front().Method->getLocation(),
5880 diag::note_pure_virtual_function)
5881 << SO->second.front().Method->getDeclName() << RD->
getDeclName();
5891 struct AbstractUsageInfo {
5898 : S(S), Record(Record),
5899 AbstractType(S.
Context.getCanonicalType(
5900 S.
Context.getTypeDeclType(Record))),
5904 if (Invalid)
return;
5912 struct CheckAbstractUsage {
5913 AbstractUsageInfo &Info;
5916 CheckAbstractUsage(AbstractUsageInfo &Info,
const NamedDecl *Ctx)
5917 : Info(Info), Ctx(Ctx) {}
5921 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5922 #define TYPELOC(CLASS, PARENT) \
5923 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5924 #include "clang/AST/TypeLocNodes.def"
5930 for (
unsigned I = 0, E = TL.
getNumParams(); I != E; ++I) {
5945 for (
unsigned I = 0, E = TL.
getNumArgs(); I != E; ++I) {
5955 #define CheckPolymorphic(Type) \
5956 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5957 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5972 return Visit(Next, Sel);
5982 T = Info.S.Context.getBaseElementType(T);
5985 if (CT != Info.AbstractType)
return;
5990 Info.S.Diag(Ctx->
getLocation(), diag::err_array_of_abstract_type)
5993 Info.S.Diag(Ctx->
getLocation(), diag::err_abstract_type_in_decl)
5996 Info.DiagnoseAbstractType();
6002 CheckAbstractUsage(*
this, D).Visit(TL, Sel);
6037 for (
auto *D : RD->
decls()) {
6038 if (D->isImplicit())
continue;
6041 if (
auto *FD = dyn_cast<FriendDecl>(D)) {
6042 D = FD->getFriendDecl();
6047 if (
auto *FD = dyn_cast<FunctionDecl>(D)) {
6049 }
else if (
auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
6053 }
else if (
auto *FD = dyn_cast<FieldDecl>(D)) {
6056 }
else if (
auto *VD = dyn_cast<VarDecl>(D)) {
6058 }
else if (
auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
6062 }
else if (
auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6064 }
else if (
auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
6075 assert(ClassAttr->
getKind() == attr::DLLExport);
6085 struct MarkingClassDllexported {
6096 ~MarkingClassDllexported() {
6099 } MarkingDllexportedContext(S, Class, ClassAttr->
getLocation());
6106 if (!
Member->hasAttr<DLLExportAttr>())
6111 auto *VD = dyn_cast<VarDecl>(
Member);
6112 if (VD && VD->getStorageClass() ==
SC_Static &&
6116 auto *MD = dyn_cast<CXXMethodDecl>(
Member);
6120 if (MD->isUserProvided()) {
6130 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6140 }
else if (MD->isExplicitlyDefaulted()) {
6149 }
else if (!MD->isTrivial() ||
6150 MD->isCopyAssignmentOperator() ||
6151 MD->isMoveAssignmentOperator()) {
6175 auto *CD = dyn_cast<CXXConstructorDecl>(
Member);
6176 if (!CD || !CD->isDefaultConstructor())
6178 auto *
Attr = CD->getAttr<DLLExportAttr>();
6184 if (!Class->isDependentContext()) {
6191 if (LastExportedDefaultCtor) {
6193 diag::err_attribute_dll_ambiguous_default_ctor)
6195 S.
Diag(CD->getLocation(), diag::note_entity_declared_at)
6196 << CD->getDeclName();
6199 LastExportedDefaultCtor = CD;
6205 bool ErrorReported =
false;
6206 auto reportIllegalClassTemplate = [&ErrorReported](
Sema &S,
6210 S.
Diag(TD->getLocation(),
6211 diag::err_cuda_device_builtin_surftex_cls_template)
6213 ErrorReported =
true;
6218 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6220 S.
Diag(Class->getLocation(),
6221 diag::err_cuda_device_builtin_surftex_ref_decl)
6223 S.
Diag(Class->getLocation(),
6224 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6228 TD = SD->getSpecializedTemplate();
6232 unsigned N = Params->
size();
6235 reportIllegalClassTemplate(S, TD);
6237 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6240 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->
getParam(0))) {
6241 reportIllegalClassTemplate(S, TD);
6243 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6247 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->
getParam(1));
6248 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6249 reportIllegalClassTemplate(S, TD);
6251 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6259 bool ErrorReported =
false;
6260 auto reportIllegalClassTemplate = [&ErrorReported](
Sema &S,
6264 S.
Diag(TD->getLocation(),
6265 diag::err_cuda_device_builtin_surftex_cls_template)
6267 ErrorReported =
true;
6272 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6274 S.
Diag(Class->getLocation(),
6275 diag::err_cuda_device_builtin_surftex_ref_decl)
6277 S.
Diag(Class->getLocation(),
6278 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6282 TD = SD->getSpecializedTemplate();
6286 unsigned N = Params->
size();
6289 reportIllegalClassTemplate(S, TD);
6291 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6294 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->
getParam(0))) {
6295 reportIllegalClassTemplate(S, TD);
6297 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6301 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->
getParam(1));
6302 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6303 reportIllegalClassTemplate(S, TD);
6305 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6310 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->
getParam(2));
6311 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6312 reportIllegalClassTemplate(S, TD);
6314 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6322 for (
auto *Method : Class->methods()) {
6323 if (Method->isUserProvided())
6336 if (
auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6337 if (
Attr *TemplateAttr =
6338 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6339 auto *A = cast<InheritableAttr>(TemplateAttr->clone(
getASTContext()));
6340 A->setInherited(
true);
6349 if (!Class->isExternallyVisible()) {
6350 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6351 << Class << ClassAttr;
6359 if (!isa<VarDecl>(
Member) && !isa<CXXMethodDecl>(
Member))
6366 diag::err_attribute_dll_member_of_dll_class)
6367 << MemberAttr << ClassAttr;
6368 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6369 Member->setInvalidDecl();
6373 if (Class->getDescribedClassTemplate())
6378 const bool ClassExported = ClassAttr->
getKind() == attr::DLLExport;
6383 const bool PropagatedImport =
6385 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6394 Class->dropAttr<DLLExportAttr>();
6428 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6437 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->
isTrivial())
6444 if (VD && PropagatedImport)
6458 if (ClassExported) {
6470 Member->addAttr(NewAttr);
6480 "friend re-decl should not already have a DLLAttr");
6512 NewAttr->setInherited(
true);
6513 BaseTemplateSpec->
addAttr(NewAttr);
6517 if (
auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6518 ImportAttr->setPropagatedToBaseTemplate();
6539 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6544 diag::note_template_class_explicit_specialization_was_here)
6545 << BaseTemplateSpec;
6548 diag::note_template_class_instantiation_was_here)
6549 << BaseTemplateSpec;
6562 if (
auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6574 if (MD->isCopyAssignmentOperator())
6577 if (MD->isMoveAssignmentOperator())
6580 if (isa<CXXDestructorDecl>(FD))
6588 case OO_ExclaimEqual:
6600 case OO_GreaterEqual:
6623 cast<CXXConstructorDecl>(FD));
6641 llvm_unreachable(
"Invalid special member.");
6659 bool CopyCtorIsTrivial =
false, CopyCtorIsTrivialForCall =
false;
6660 bool DtorIsTrivialForCall =
false;
6671 CopyCtorIsTrivial =
true;
6673 CopyCtorIsTrivialForCall =
true;
6677 if (CD->isCopyConstructor() && !CD->isDeleted() &&
6678 !CD->isIneligibleOrNotSelected()) {
6679 if (CD->isTrivial())
6680 CopyCtorIsTrivial =
true;
6681 if (CD->isTrivialForCall())
6682 CopyCtorIsTrivialForCall =
true;
6690 DtorIsTrivialForCall =
true;
6692 if (!DD->isDeleted() && DD->isTrivialForCall())
6693 DtorIsTrivialForCall =
true;
6697 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6711 uint64_t TypeSize = isAArch64 ? 128 : 64;
6713 if (CopyCtorIsTrivial &&
6723 bool HasNonDeletedCopyOrMove =
false;
6729 HasNonDeletedCopyOrMove =
true;
6736 HasNonDeletedCopyOrMove =
true;
6744 if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
6747 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6748 if (CD && CD->isCopyOrMoveConstructor())
6749 HasNonDeletedCopyOrMove =
true;
6750 else if (!isa<CXXDestructorDecl>(MD))
6753 if (!MD->isTrivialForCall())
6757 return HasNonDeletedCopyOrMove;
6768 bool IssuedDiagnostic =
false;
6771 if (!IssuedDiagnostic) {
6773 IssuedDiagnostic =
true;
6775 S.
Diag(O->getLocation(), diag::note_overridden_virtual_function);
6778 return IssuedDiagnostic;
6793 AbstractUsageInfo Info(*
this, Record);
6803 bool Complained =
false;
6804 for (
const auto *F : Record->
fields()) {
6805 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6808 if (F->getType()->isReferenceType() ||
6809 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6816 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6817 << F->getType()->isReferenceType()
6818 << F->getDeclName();
6836 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6838 isa<IndirectFieldDecl>(D)) {
6839 Diag((*I)->getLocation(), diag::err_member_name_of_class)
6850 !Record->
hasAttr<FinalAttr>())
6856 if (FinalAttr *FA = Record->
getAttr<FinalAttr>()) {
6858 << FA->isSpelledAsSealed();
6864 if (!Record->
hasAttr<FinalAttr>()) {
6866 if (
const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6867 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6868 << FA->isSpelledAsSealed()
6871 (FA->isSpelledAsSealed() ?
" sealed" :
" final"));
6873 diag::note_final_dtor_non_final_class_silence)
6880 if (Record->
hasAttr<TrivialABIAttr>())
6885 bool HasTrivialABI = Record->
hasAttr<TrivialABIAttr>();
6898 auto CheckCompletedMemberFunction = [&](
CXXMethodDecl *MD) {
6909 MD->
isDeleted() ? diag::err_deleted_override
6910 : diag::err_non_deleted_override,
6914 if (MD->isDefaulted() && MD->isDeleted())
6923 MD->isConsteval() ? diag::err_consteval_override
6924 : diag::err_non_consteval_override,
6926 return MD->isConsteval() !=
V->isConsteval();
6928 if (MD->isDefaulted() && MD->isDeleted())
6935 auto CheckForDefaultedFunction = [&](
FunctionDecl *FD) ->
bool {
6936 if (!FD || FD->
isInvalidDecl() || !FD->isExplicitlyDefaulted())
6942 DefaultedSecondaryComparisons.push_back(FD);
6952 bool Incomplete = CheckForDefaultedFunction(M);
6961 if (!M->isImplicit() && !M->isUserProvided()) {
6966 M->setTrivialForCall(
6977 M->setTrivialForCall(HasTrivialABI);
6981 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6982 M->hasAttr<DLLExportAttr>()) {
6987 M->dropAttr<DLLExportAttr>();
6989 if (M->hasAttr<DLLExportAttr>()) {
6998 if (CSM !=
CXXInvalid && !M->isDeleted() && M->isDefaulted() &&
6999 M->isConstexpr() && M->size_overridden_methods())
7003 CheckCompletedMemberFunction(M);
7012 CompleteMemberFunction(Dtor);
7014 bool HasMethodWithOverrideControl =
false,
7015 HasOverridingMethodWithoutOverrideControl =
false;
7016 for (
auto *D : Record->
decls()) {
7017 if (
auto *M = dyn_cast<CXXMethodDecl>(D)) {
7025 if (M->hasAttr<OverrideAttr>())
7026 HasMethodWithOverrideControl =
true;
7027 else if (M->size_overridden_methods() > 0)
7028 HasOverridingMethodWithoutOverrideControl =
true;
7031 if (!isa<CXXDestructorDecl>(M))
7032 CompleteMemberFunction(M);
7033 }
else if (
auto *F = dyn_cast<FriendDecl>(D)) {
7034 CheckForDefaultedFunction(
7035 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
7039 if (HasOverridingMethodWithoutOverrideControl) {
7040 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
7041 for (
auto *M : Record->
methods())
7046 for (
FunctionDecl *FD : DefaultedSecondaryComparisons) {
7050 if (
auto *MD = dyn_cast<CXXMethodDecl>(FD))
7051 CheckCompletedMemberFunction(MD);
7075 bool ClangABICompat4 =
7104 if (Record->
hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7106 else if (Record->
hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7122 unsigned FieldQuals,
bool ConstRHS) {
7123 unsigned LHSQuals = 0;
7125 LHSQuals = FieldQuals;
7127 unsigned RHSQuals = FieldQuals;
7148 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7154 : S(S), UseLoc(UseLoc) {
7155 bool DiagnosedMultipleConstructedBases =
false;
7161 for (
auto *D : Shadow->
redecls()) {
7162 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7163 auto *DNominatedBase = DShadow->getNominatedBaseClass();
7164 auto *DConstructedBase = DShadow->getConstructedBaseClass();
7166 InheritedFromBases.insert(
7167 std::make_pair(DNominatedBase->getCanonicalDecl(),
7168 DShadow->getNominatedBaseClassShadowDecl()));
7169 if (DShadow->constructsVirtualBase())
7170 InheritedFromBases.insert(
7171 std::make_pair(DConstructedBase->getCanonicalDecl(),
7172 DShadow->getConstructedBaseClassShadowDecl()));
7174 assert(DNominatedBase == DConstructedBase);
7179 if (!ConstructedBase) {
7180 ConstructedBase = DConstructedBase;
7181 ConstructedBaseIntroducer = D->getIntroducer();
7182 }
else if (ConstructedBase != DConstructedBase &&
7184 if (!DiagnosedMultipleConstructedBases) {
7185 S.
Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7188 diag::note_ambiguous_inherited_constructor_using)
7190 DiagnosedMultipleConstructedBases =
true;
7192 S.
Diag(D->getIntroducer()->getLocation(),
7193 diag::note_ambiguous_inherited_constructor_using)
7194 << DConstructedBase;
7198 if (DiagnosedMultipleConstructedBases)
7205 std::pair<CXXConstructorDecl *, bool>
7207 auto It = InheritedFromBases.find(
Base->getCanonicalDecl());
7208 if (It == InheritedFromBases.end())
7209 return std::make_pair(
nullptr,
false);
7213 return std::make_pair(
7215 It->second->constructsVirtualBase());
7218 return std::make_pair(Ctor,
false);
7237 if (InheritedCtor) {
7240 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7242 return BaseCtor->isConstexpr();
7310 if (Ctor && ClassDecl->
isUnion())
7329 for (
const auto &B : ClassDecl->
bases()) {
7335 InheritedCtor, Inherited))
7346 for (
const auto *F : ClassDecl->
fields()) {
7347 if (F->isInvalidDecl())
7353 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7356 ConstArg && !F->isMutable()))
7370 struct ComputingExceptionSpec {
7381 ~ComputingExceptionSpec() {
7400 if (DFK.isSpecialMember())
7402 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
nullptr);
7403 if (DFK.isComparison())
7405 DFK.asComparison());
7407 auto *CD = cast<CXXConstructorDecl>(FD);
7408 assert(CD->getInheritedConstructor() &&
7409 "only defaulted functions and inherited constructors have implicit "
7412 S, Loc, CD->getInheritedConstructor().getShadowDecl());
7439 auto ESI = IES.getExceptionSpec();
7471 "not an explicitly-defaulted special member");
7481 bool HadError =
false;
7494 bool ShouldDeleteForTypeMismatch =
false;
7495 unsigned ExpectedParams = 1;
7506 if (DeleteOnTypeMismatch)
7507 ShouldDeleteForTypeMismatch =
true;
7517 bool CanHaveConstParam =
false;
7526 ReturnType =
Type->getReturnType();
7534 Diag(MD->
getLocation(), diag::err_defaulted_special_member_return_type)
7540 if (
Type->getMethodQuals().hasConst() ||
Type->getMethodQuals().hasVolatile()) {
7541 if (DeleteOnTypeMismatch)
7542 ShouldDeleteForTypeMismatch =
true;
7553 bool HasConstParam =
false;
7560 if (DeleteOnTypeMismatch)
7561 ShouldDeleteForTypeMismatch =
true;
7564 diag::err_defaulted_special_member_volatile_param) << CSM;
7569 if (HasConstParam && !CanHaveConstParam) {
7570 if (DeleteOnTypeMismatch)
7571 ShouldDeleteForTypeMismatch =
true;
7574 diag::err_defaulted_special_member_copy_const_param)
7580 diag::err_defaulted_special_member_move_const_param)
7585 }
else if (ExpectedParams) {
7617 : isa<CXXConstructorDecl>(MD))) &&
7621 ? diag::err_incorrect_defaulted_consteval
7622 : diag::err_incorrect_defaulted_constexpr)
7638 if (!
Type->hasExceptionSpec()) {
7656 if (ShouldDeleteForTypeMismatch) {
7661 Diag(DefaultLoc, diag::note_replace_equals_default_to_delete)
7665 if (ShouldDeleteForTypeMismatch && !HadError) {
7667 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
7673 Diag(MD->
getLocation(), diag::err_out_of_line_default_deletes) << CSM;
7674 assert(!ShouldDeleteForTypeMismatch &&
"deleted non-first decl");
7696 template<
typename Derived,
typename ResultList,
typename Result,
7698 class DefaultedComparisonVisitor {
7704 : S(S), RD(RD), FD(FD), DCK(DCK) {
7708 Fns.assign(Info->getUnqualifiedLookups().begin(),
7709 Info->getUnqualifiedLookups().end());
7713 ResultList visit() {
7722 llvm_unreachable(
"not a defaulted comparison");
7726 getDerived().visitSubobjects(Results, RD, ParamLvalType.
getQualifiers());
7731 Results.add(getDerived().visitExpandedSubobject(
7732 ParamLvalType, getDerived().getCompleteObject()));
7735 llvm_unreachable(
"");
7739 Derived &getDerived() {
return static_cast<Derived&
>(*this); }
7745 bool visitSubobjects(ResultList &Results,
CXXRecordDecl *Record,
7750 if (Results.add(getDerived().visitSubobject(
7758 if (
Field->isAnonymousStructOrUnion()) {
7759 if (visitSubobjects(Results,
Field->getType()->getAsCXXRecordDecl(),
7767 if (
Field->isMutable())
7772 if (Results.add(getDerived().visitSubobject(
7773 FieldType, getDerived().getField(Field))))
7781 Result visitSubobject(
QualType Type, Subobject Subobj) {
7784 if (
auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
7785 return getDerived().visitSubobjectArray(CAT->getElementType(),
7786 CAT->getSize(), Subobj);
7787 return getDerived().visitExpandedSubobject(
Type, Subobj);
7792 return getDerived().visitSubobject(
Type, Subobj);
7805 struct DefaultedComparisonInfo {
7810 static DefaultedComparisonInfo deleted() {
7811 DefaultedComparisonInfo
Deleted;
7816 bool add(
const DefaultedComparisonInfo &R) {
7826 struct DefaultedComparisonSubobject {
7834 class DefaultedComparisonAnalyzer
7835 :
public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
7836 DefaultedComparisonInfo,
7837 DefaultedComparisonInfo,
7838 DefaultedComparisonSubobject> {
7840 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
7843 DiagnosticKind Diagnose;
7846 using Base = DefaultedComparisonVisitor;
7847 using Result = DefaultedComparisonInfo;
7848 using Subobject = DefaultedComparisonSubobject;
7854 DiagnosticKind Diagnose = NoDiagnostics)
7855 :
Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
7864 if (Diagnose == ExplainDeleted) {
7868 return Result::deleted();
7871 return Base::visit();
7875 Subobject getCompleteObject() {
7876 return Subobject{Subobject::CompleteObject, RD, FD->
getLocation()};
7881 Base->getBaseTypeLoc()};
7885 return Subobject{Subobject::Member,
Field,
Field->getLocation()};
7888 Result visitExpandedSubobject(
QualType Type, Subobject Subobj) {
7893 if (Diagnose == ExplainDeleted) {
7894 S.
Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
7897 return Result::deleted();
7902 Expr *Args[] = {&Xi, &Xi};
7906 assert(OO !=
OO_None &&
"not an overloaded operator!");
7907 return visitBinaryOperator(OO, Args, Subobj);
7921 !SpaceshipCandidates));
7926 CandidateSet.exclude(FD);
7928 if (Args[0]->getType()->isOverloadableType())
7939 switch (CandidateSet.BestViableFunction(S, FD->
getLocation(), Best)) {
7947 !Best->RewriteKind) {
7948 if (Diagnose == ExplainDeleted) {
7949 if (Best->Function) {
7950 S.
Diag(Best->Function->getLocation(),
7951 diag::note_defaulted_comparison_not_rewritten_callee)
7954 assert(Best->Conversions.size() == 2 &&
7955 Best->Conversions[0].isUserDefined() &&
7956 "non-user-defined conversion from class to built-in "
7958 S.
Diag(Best->Conversions[0]
7959 .UserDefined.FoundConversionFunction.getDecl()
7961 diag::note_defaulted_comparison_not_rewritten_conversion)
7965 return Result::deleted();
7975 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
7976 if (ArgClass && Best->FoundDecl.getDecl() &&
7977 Best->FoundDecl.getDecl()->isCXXClassMember()) {
7978 QualType ObjectType = Subobj.Kind == Subobject::Member
7979 ? Args[0]->getType()
7982 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
7983 Diagnose == ExplainDeleted
7984 ? S.
PDiag(diag::note_defaulted_comparison_inaccessible)
7985 << FD << Subobj.Kind << Subobj.Decl
7987 return Result::deleted();
7990 bool NeedsDeducing =
7998 assert(!BestFD->isDeleted() &&
"wrong overload resolution result");
8000 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
8001 if (Subobj.Kind != Subobject::CompleteObject)
8002 S.
Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
8003 << Subobj.
Kind << Subobj.Decl;
8004 S.
Diag(BestFD->getLocation(),
8005 diag::note_defaulted_comparison_not_constexpr_here);
8007 return Result::deleted();
8009 R.Constexpr &= BestFD->isConstexpr();
8011 if (NeedsDeducing) {
8016 if (BestFD->getReturnType()->isUndeducedType() &&
8022 if (Diagnose == NoDiagnostics) {
8025 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
8026 << Subobj.
Kind << Subobj.Decl;
8029 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
8030 << Subobj.
Kind << Subobj.Decl;
8031 S.
Diag(BestFD->getLocation(),
8032 diag::note_defaulted_comparison_cannot_deduce_callee)
8033 << Subobj.
Kind << Subobj.Decl;
8035 return Result::deleted();
8038 BestFD->getCallResultType());
8040 if (Diagnose == ExplainDeleted) {
8041 S.
Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
8042 << Subobj.
Kind << Subobj.Decl
8043 << BestFD->getCallResultType().withoutLocalFastQualifiers();
8044 S.
Diag(BestFD->getLocation(),
8045 diag::note_defaulted_comparison_cannot_deduce_callee)
8046 << Subobj.
Kind << Subobj.Decl;
8048 return Result::deleted();
8050 R.Category = Info->Kind;
8053 QualType T = Best->BuiltinParamTypes[0];
8054 assert(T == Best->BuiltinParamTypes[1] &&
8055 "builtin comparison for different types?");
8056 assert(Best->BuiltinParamTypes[2].isNull() &&
8057 "invalid builtin comparison");
8059 if (NeedsDeducing) {
8060 std::optional<ComparisonCategoryType> Cat =
8062 assert(Cat &&
"no category for builtin comparison?");
8073 if (Diagnose == ExplainDeleted) {
8076 Kind = OO == OO_EqualEqual ? 1 : 2;
8077 CandidateSet.NoteCandidates(
8079 Subobj.Loc, S.
PDiag(diag::note_defaulted_comparison_ambiguous)
8080 << FD <<
Kind << Subobj.Kind << Subobj.Decl),
8083 R = Result::deleted();
8087 if (Diagnose == ExplainDeleted) {
8090 !Best->RewriteKind) {
8091 S.
Diag(Best->Function->getLocation(),
8092 diag::note_defaulted_comparison_not_rewritten_callee)
8096 diag::note_defaulted_comparison_calls_deleted)
8097 << FD << Subobj.
Kind << Subobj.Decl;
8101 R = Result::deleted();
8107 if (OO == OO_Spaceship &&
8111 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
8113 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
8117 if (Diagnose == ExplainDeleted) {
8118 S.
Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
8119 << FD << (OO == OO_ExclaimEqual) << Subobj.
Kind << Subobj.Decl;
8123 if (SpaceshipCandidates) {
8124 SpaceshipCandidates->NoteCandidates(
8129 diag::note_defaulted_comparison_no_viable_function_synthesized)
8130 << (OO == OO_EqualEqual ? 0 : 1);
8133 CandidateSet.NoteCandidates(
8138 R = Result::deleted();
8147 struct StmtListResult {
8148 bool IsInvalid =
false;
8152 IsInvalid |= S.isInvalid();
8155 Stmts.push_back(S.get());
8162 class DefaultedComparisonSynthesizer
8163 :
public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8164 StmtListResult, StmtResult,
8165 std::pair<ExprResult, ExprResult>> {
8167 unsigned ArrayDepth = 0;
8170 using Base = DefaultedComparisonVisitor;
8171 using ExprPair = std::pair<ExprResult, ExprResult>;
8178 :
Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8184 StmtListResult Stmts = visit();
8185 if (Stmts.IsInvalid)
8191 llvm_unreachable(
"not a defaulted comparison");
8202 auto OldStmts = std::move(Stmts.Stmts);
8203 Stmts.Stmts.clear();
8206 auto FinishCmp = [&] {
8207 if (
Expr *Prior = CmpSoFar.
get()) {
8209 if (RetVal.
isUnset() && Stmts.Stmts.empty())
8212 else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8218 for (
Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8219 Expr *E = dyn_cast<Expr>(EAsStmt);
8222 if (FinishCmp() || Stmts.add(EAsStmt))
8237 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8255 RetVal = getDecl(EqualVD);
8258 RetVal = buildStaticCastToR(RetVal.
get());
8264 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8290 ExprPair getCompleteObject() {
8293 if (isa<CXXMethodDecl>(FD)) {
8299 LHS = getParam(Param++);
8307 ExprPair Obj = getCompleteObject();
8308 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8318 ExprPair Obj = getCompleteObject();
8319 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8342 assert(!False.
isInvalid() &&
"should never fail");
8344 if (ReturnFalse.isInvalid())
8362 llvm::raw_svector_ostream
OS(Str);
8363 OS <<
"i" << ArrayDepth;
8374 auto IterRef = [&] {
8378 assert(!Ref.
isInvalid() &&
"can't reference our own variable?");
8384 Loc, BO_NE, IterRef(),
8386 assert(!Cond.
isInvalid() &&
"should never fail");
8390 assert(!
Inc.isInvalid() &&
"should never fail");
8398 Subobj.first = Index(Subobj.first);
8399 Subobj.second = Index(Subobj.second);
8406 if (Substmt.isInvalid())
8412 if (
Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8414 "should have non-expression statement");
8415 Substmt = buildIfNotCondReturnFalse(ElemCmp);
8416 if (Substmt.isInvalid())
8429 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8437 Obj.second.get(),
true,
8446 llvm_unreachable(
"not a defaulted comparison");
8461 Op = buildStaticCastToR(Op.
get());
8486 if (
Comp.isInvalid())
8494 VDRef = getDecl(VD);
8513 llvm_unreachable(
"");
8519 assert(!R->
isUndeducedType() &&
"type should have been deduced already");
8550 if (Op == OO_Spaceship) {
8551 Lookup(OO_ExclaimEqual);
8553 Lookup(OO_EqualEqual);
8580 bool IsMethod = isa<CXXMethodDecl>(FD);
8582 auto *MD = cast<CXXMethodDecl>(FD);
8583 assert(!MD->
isStatic() &&
"comparison function cannot be a static member");
8605 FPT->getParamTypes(), EPI));
8613 <<
int(IsMethod) <<
int(DCK);
8619 QualType ParmTy = Param->getType();
8625 bool Ok = !IsMethod;
8630 CTy = Ref->getPointeeType();
8641 }
else if (
auto *CRD = CTy->getAsRecordDecl()) {
8642 RD = cast<CXXRecordDecl>(CRD);
8658 <<
int(DCK) << ParmTy << RefTy <<
int(!IsMethod) << PlainTy
8659 << Param->getSourceRange();
8661 assert(!IsMethod &&
"should know expected type for method");
8663 diag::err_defaulted_comparison_param_unknown)
8664 <<
int(DCK) << ParmTy << Param->getSourceRange();
8670 Diag(FD->
getLocation(), diag::err_defaulted_comparison_param_mismatch)
8672 << ParmTy << Param->getSourceRange();
8677 assert(RD &&
"must have determined class");
8686 diag::err_defaulted_comparison_not_friend,
int(DCK),
8691 return FD->getCanonicalDecl() ==
8692 F->getFriendDecl()->getCanonicalDecl();
8695 <<
int(DCK) <<
int(0) << RD;
8707 Diag(FD->
getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8717 RT->getContainedDeducedType() &&
8719 RT->getContainedAutoType()->isConstrained())) {
8721 diag::err_defaulted_comparison_deduced_return_type_not_auto)
8733 DefaultedComparisonInfo Info =
8734 DefaultedComparisonAnalyzer(*
this, RD, FD, DCK).visit();
8748 DefaultedComparisonAnalyzer(*
this, RD, FD, DCK,
8749 DefaultedComparisonAnalyzer::ExplainDeleted)
8760 diag::note_previous_declaration);
8772 DefaultedComparisonAnalyzer(*
this, RD, FD, DCK,
8773 DefaultedComparisonAnalyzer::ExplainDeleted)
8812 diag::err_incorrect_defaulted_comparison_constexpr)
8814 DefaultedComparisonAnalyzer(*
this, RD, FD, DCK,
8815 DefaultedComparisonAnalyzer::ExplainConstexpr)
8836 EPI.ExceptionSpec.SourceDecl = FD;
8838 FPT->getParamTypes(), EPI));
8853 EqualEqual->setImplicit();
8868 Scope.addContextNote(UseLoc);
8875 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
8879 DefaultedComparisonSynthesizer(*
this, RD, FD, DCK, BodyLoc).build();
8893 L->CompletedImplicitDefinition(FD);
8900 ComputingExceptionSpec CES(S, FD, Loc);
8927 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
8928 if (!Body.isInvalid())
8949 for (
auto &Check : Overriding)
8961 template<
typename Derived>
8962 struct SpecialMemberVisitor {
8969 bool IsConstructor =
false, IsAssignment =
false, ConstArg =
false;
8973 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
8978 IsConstructor =
true;
8982 IsAssignment =
true;
8987 llvm_unreachable(
"invalid special member kind");
8993 ConstArg = RT->getPointeeType().isConstQualified();
8997 Derived &getDerived() {
return static_cast<Derived&
>(*this); }
9000 bool isMove()
const {
9006 unsigned Quals,
bool IsMutable) {
9008 ConstArg && !IsMutable);
9018 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
9025 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
9032 return B->getBaseTypeLoc();
9034 return Subobj.get<
FieldDecl*>()->getLocation();
9039 VisitNonVirtualBases,
9044 VisitPotentiallyConstructedBases,
9050 bool visit(BasesToVisit Bases) {
9053 if (Bases == VisitPotentiallyConstructedBases)
9054 Bases = RD->
isAbstract() ? VisitNonVirtualBases : VisitAllBases;
9056 for (
auto &B : RD->
bases())
9057 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
9058 getDerived().visitBase(&B))
9061 if (Bases == VisitAllBases)
9062 for (
auto &B : RD->
vbases())
9063 if (getDerived().visitBase(&B))
9066 for (
auto *F : RD->
fields())
9067 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
9068 getDerived().visitField(F))
9077 struct SpecialMemberDeletionInfo
9078 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
9083 bool AllFieldsAreConst;
9088 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9089 Loc(MD->getLocation()), AllFieldsAreConst(
true) {}
9100 bool visitField(
FieldDecl *Field) {
return shouldDeleteForField(Field); }
9103 bool shouldDeleteForField(
FieldDecl *FD);
9104 bool shouldDeleteForAllConstMembers();
9106 bool shouldDeleteForClassSubobject(
CXXRecordDecl *Class, Subobject Subobj,
9108 bool shouldDeleteForSubobjectCall(Subobject Subobj,
9110 bool IsDtorCallInCtor);
9118 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9139 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9141 bool IsDtorCallInCtor) {
9148 DiagKind = !
Decl ? 0 : 1;
9151 else if (!isAccessible(Subobj,
Decl))
9153 else if (!IsDtorCallInCtor && Field &&
Field->getParent()->isUnion() &&
9154 !
Decl->isTrivial()) {
9169 diag::note_deleted_special_member_class_subobject)
9170 << getEffectiveCSM() << MD->
getParent() <<
true
9171 <<
Field << DiagKind << IsDtorCallInCtor <<
false;
9175 diag::note_deleted_special_member_class_subobject)
9176 << getEffectiveCSM() << MD->
getParent() <<
false
9177 <<
Base->getType() << DiagKind << IsDtorCallInCtor
9191 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9194 bool IsMutable =
Field &&
Field->isMutable();
9211 Field &&
Field->hasInClassInitializer()) &&
9212 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
9219 if (IsConstructor) {
9222 false,
false,
false,
false,
false);
9223 if (shouldDeleteForSubobjectCall(Subobj, SMOR,
true))
9230 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9244 auto *ParentClass = cast<CXXRecordDecl>(FD->
getParent());
9246 diag::note_deleted_special_member_class_subobject)
9247 << getEffectiveCSM() << ParentClass <<
true
9248 << FD << 4 <<
false <<
true;
9265 if (
auto *BaseCtor = SMOR.
getMethod()) {
9270 if (BaseCtor->isDeleted() && Diagnose) {
9272 diag::note_deleted_special_member_class_subobject)
9273 << getEffectiveCSM() << MD->
getParent() <<
false
9274 <<
Base->getType() << 1 <<
false
9278 return BaseCtor->isDeleted();
9280 return shouldDeleteForClassSubobject(BaseClass,
Base, 0);
9285 bool SpecialMemberDeletionInfo::shouldDeleteForField(
FieldDecl *FD) {
9289 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9297 S.
Diag(FD->
getLocation(), diag::note_deleted_default_ctor_uninit_field)
9298 << !!ICI << MD->
getParent() << FD << FieldType << 0;
9308 S.
Diag(FD->
getLocation(), diag::note_deleted_default_ctor_uninit_field)
9314 AllFieldsAreConst =
false;
9320 S.
Diag(FD->
getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9324 }
else if (IsAssignment) {
9329 << isMove() << MD->
getParent() << FD << FieldType << 0;
9344 if (!inUnion() && FieldRecord->
isUnion() &&
9346 bool AllVariantFieldsAreConst =
true;
9349 for (
auto *UI : FieldRecord->
fields()) {
9352 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9356 AllVariantFieldsAreConst =
false;
9359 if (UnionFieldRecord &&
9360 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9370 diag::note_deleted_default_ctor_all_const)
9381 if (shouldDeleteForClassSubobject(FieldRecord, FD,
9392 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9396 bool AnyFields =
false;
9398 if ((AnyFields = !F->isUnnamedBitfield()))
9404 diag::note_deleted_default_ctor_all_const)
9454 bool DeletesOnlyMatchingCopy =
9460 if (!Diagnose)
return true;
9463 for (
auto *I : RD->
ctors()) {
9464 if (I->isMoveConstructor()) {
9465 UserDeclaredMove = I;
9469 assert(UserDeclaredMove);
9472 if (!Diagnose)
return true;
9475 for (
auto *I : RD->
methods()) {
9476 if (I->isMoveAssignmentOperator()) {
9477 UserDeclaredMove = I;
9481 assert(UserDeclaredMove);
9484 if (UserDeclaredMove) {
9486 diag::note_deleted_copy_user_declared_move)
9504 OperatorDelete,
false)) {
9511 SpecialMemberDeletionInfo SMI(*
this, MD, CSM, ICI, Diagnose);
9519 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9520 : SMI.VisitPotentiallyConstructedBases))
9523 if (SMI.shouldDeleteForAllConstMembers())
9539 SMI.ConstArg, Diagnose);
9547 assert(DFK &&
"not a defaultable function");
9554 DefaultedComparisonAnalyzer(
9556 DFK.
asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9578 *Selected =
nullptr;
9582 llvm_unreachable(
"not a special member");
9600 for (
auto *CI : RD->
ctors()) {
9601 if (!CI->isDefaultConstructor())
9608 *Selected = DefCtor;
9641 }
else if (!Selected) {
9649 goto NeedOverloadResolution;
9659 }
else if (!Selected) {
9664 goto NeedOverloadResolution;
9668 NeedOverloadResolution:
9696 llvm_unreachable(
"unknown special method kind");
9700 for (
auto *CI : RD->
ctors())
9701 if (!CI->isImplicit())
9705 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
9708 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
9738 ConstRHS, TAH, Diagnose ? &Selected :
nullptr))
9746 S.
Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
9749 S.
Diag(CD->getLocation(), diag::note_user_declared_ctor);
9750 }
else if (!Selected)
9751 S.
Diag(SubobjLoc, diag::note_nontrivial_no_copy)
9753 else if (Selected->isUserProvided()) {
9755 S.
Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
9756 <<
Kind << SubType.getUnqualifiedType() << CSM;
9758 S.
Diag(SubobjLoc, diag::note_nontrivial_user_provided)
9759 <<
Kind << SubType.getUnqualifiedType() << CSM;
9760 S.
Diag(Selected->getLocation(), diag::note_declared_at);
9764 S.
Diag(SubobjLoc, diag::note_nontrivial_subobject)
9765 <<
Kind << SubType.getUnqualifiedType() << CSM;
9783 for (
const auto *FI : RD->
fields()) {
9784 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
9790 if (FI->isAnonymousStructOrUnion()) {
9792 CSM, ConstArg, TAH, Diagnose))
9803 S.
Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
9814 S.
Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
9819 bool ConstRHS = ConstArg && !FI->isMutable();
9848 bool ConstArg =
false;
9876 ClangABICompat14)) {
9906 llvm_unreachable(
"not a special member");
9912 diag::note_nontrivial_default_arg)
9931 for (
const auto &BI : RD->
bases())
9977 for (
const auto *MI : RD->
methods()) {
9978 if (MI->isVirtual()) {
9980 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
9985 llvm_unreachable(
"dynamic class with no vbases and no virtual functions");
9993 struct FindHiddenVirtualMethod {
10001 static bool CheckMostOverridenMethods(
10003 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
10007 if (CheckMostOverridenMethods(O, Methods))
10023 bool foundSameNameMethod =
false;
10030 foundSameNameMethod =
true;
10047 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
10048 overloadedMethods.push_back(MD);
10052 if (foundSameNameMethod)
10053 OverloadedMethods.append(overloadedMethods.begin(),
10054 overloadedMethods.end());
10055 return foundSameNameMethod;
10062 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
10080 FindHiddenVirtualMethod FHVM;
10091 ND = shad->getTargetDecl();
10097 OverloadedMethods = FHVM.OverloadedMethods;
10102 for (
unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
10105 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10122 if (!OverloadedMethods.empty()) {
10124 << MD << (OverloadedMethods.size() > 1);
10131 auto PrintDiagAndRemoveAttr = [&](
unsigned N) {
10134 Diag(RD.
getAttr<TrivialABIAttr>()->getLocation(),
10135 diag::ext_cannot_use_trivial_abi) << &RD;
10136 Diag(RD.
getAttr<TrivialABIAttr>()->getLocation(),
10137 diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10143 auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10155 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10160 if (!HasNonDeletedCopyOrMoveConstructor()) {
10161 PrintDiagAndRemoveAttr(0);
10167 PrintDiagAndRemoveAttr(1);
10171 for (
const auto &B : RD.
bases()) {
10174 if (!B.getType()->isDependentType() &&
10175 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10176 PrintDiagAndRemoveAttr(2);
10180 if (B.isVirtual()) {
10181 PrintDiagAndRemoveAttr(3);
10186 for (
const auto *FD : RD.
fields()) {
10191 PrintDiagAndRemoveAttr(4);
10196 if (!RT->isDependentType() &&
10197 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
10198 PrintDiagAndRemoveAttr(5);
10213 if (AL.getKind() != ParsedAttr::AT_Visibility)
10216 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10224 LBrac, RBrac, AttrList);
10241 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
10246 Spaceships.clear();
10252 Spaceships.push_back(FD);
10261 if (
auto *FD = dyn_cast<FunctionDecl>(ND))
10262 if (FD->isExplicitlyDefaulted())
10263 Spaceships.push_back(FD);
10363 DefaultedSpaceships);
10364 for (
auto *FD : DefaultedSpaceships)
10371 llvm::function_ref<
Scope *()> EnterScope) {
10379 DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10382 for (
unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10383 ParameterLists.push_back(DD->getTemplateParameterList(i));
10387 ParameterLists.push_back(FTD->getTemplateParameters());
10388 }
else if (
VarDecl *VD = dyn_cast<VarDecl>(D)) {
10392 ParameterLists.push_back(VTD->getTemplateParameters());
10393 else if (
auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10394 ParameterLists.push_back(PSD->getTemplateParameters());
10396 }
else if (
TagDecl *TD = dyn_cast<TagDecl>(D)) {
10397 for (
unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10398 ParameterLists.push_back(TD->getTemplateParameterList(i));
10402 ParameterLists.push_back(CTD->getTemplateParameters());
10403 else if (
auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10404 ParameterLists.push_back(PSD->getTemplateParameters());
10409 unsigned Count = 0;
10410 Scope *InnermostTemplateScope =
nullptr;
10414 if (Params->size() == 0)
10417 InnermostTemplateScope = EnterScope();
10419 if (Param->getDeclName()) {
10420 InnermostTemplateScope->
AddDecl(Param);
10428 if (InnermostTemplateScope) {
10429 assert(LookupDC &&
"no enclosing DeclContext for template lookup");
10437 if (!RecordD)
return;
10444 if (!RecordD)
return;
10518 bool DiagOccured =
false;
10520 [DiagID, &S, &DiagOccured](
DeclSpec::TQ, StringRef QualName,
10527 DiagOccured =
true;
10605 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10607 return Constructor->setInvalidDecl();
10614 if (!Constructor->isInvalidDecl() &&
10615 Constructor->hasOneParamOrDefaultArgs() &&
10616 Constructor->getTemplateSpecializationKind() !=
10618 QualType ParamType = Constructor->getParamDecl(0)->getType();
10621 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10622 const char *ConstRef
10623 = Constructor->getParamDecl(0)->getIdentifier() ?
"const &"
10625 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10630 Constructor->setInvalidDecl();
10641 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10644 if (!Destructor->isImplicit())
10645 Loc = Destructor->getLocation();
10652 Expr *ThisArg =
nullptr;
10657 if (OperatorDelete->isDestroyingOperatorDelete()) {
10658 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10665 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10666 assert(!
This.isInvalid() &&
"couldn't form 'this' expr in dtor?");
10668 if (
This.isInvalid()) {
10671 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10674 ThisArg =
This.get();
10680 Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10703 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10706 if (TST->isTypeAlias())
10708 << DeclaratorType << 1;
10802 if (
After.isInvalid())
10862 if (Proto->getNumParams() > 0) {
10868 }
else if (Proto->isVariadic()) {
10875 if (Proto->getReturnType() != ConvType) {
10876 bool NeedsTypedef =
false;
10880 bool PastFunctionChunk =
false;
10882 switch (Chunk.Kind) {
10884 if (!PastFunctionChunk) {
10885 if (Chunk.Fun.HasTrailingReturnType) {
10890 PastFunctionChunk =
true;
10895 NeedsTypedef =
true;
10917 auto &&DB =
Diag(Loc, diag::err_conv_function_with_complex_decl);
10918 DB << Before <<
After;
10920 if (!NeedsTypedef) {
10924 if (
After.isInvalid() && ConvTSI) {
10932 }
else if (!Proto->getReturnType()->isDependentType()) {
10933 DB << 1 << Proto->getReturnType();
10935 DB << 2 << Proto->getReturnType();
10946 ConvType = Proto->getReturnType();
10967 Proto->getExtProtoInfo());
10973 ? diag::warn_cxx98_compat_explicit_conversion_functions
10974 : diag::ext_explicit_conversion_functions)
10983 assert(Conversion &&
"Expected to receive a conversion function declaration");
11006 if (ConvType == ClassType)
11011 << ClassType << ConvType;
11014 << ClassType << ConvType;
11019 return ConversionTemplate;
11027 struct BadSpecifierDiagnoser {
11030 ~BadSpecifierDiagnoser() {
11034 template<
typename T>
void check(
SourceLocation SpecLoc, T Spec) {
11038 return check(SpecLoc,
11044 if (!Specifiers.empty()) Specifiers +=
" ";
11045 Specifiers += Spec;
11062 assert(GuidedTemplateDecl &&
"missing template decl for deduction guide");
11070 << GuidedTemplateDecl;
11071 Diag(GuidedTemplateDecl->
getLocation(), diag::note_template_decl_here);
11076 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
11077 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
11078 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
11079 BadSpecifierDiagnoser Diagnoser(
11081 diag::err_deduction_guide_invalid_specifier);
11083 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
11084 DS.ClearStorageClassSpecs();
11088 Diagnoser.check(DS.getInlineSpecLoc(),
"inline");
11089 Diagnoser.check(DS.getNoreturnSpecLoc(),
"_Noreturn");
11090 Diagnoser.check(DS.getConstexprSpecLoc(),
"constexpr");
11091 DS.ClearConstexprSpec();
11093 Diagnoser.check(DS.getConstSpecLoc(),
"const");
11094 Diagnoser.check(DS.getRestrictSpecLoc(),
"__restrict");
11095 Diagnoser.check(DS.getVolatileSpecLoc(),
"volatile");
11096 Diagnoser.check(DS.getAtomicSpecLoc(),
"_Atomic");
11097 Diagnoser.check(DS.getUnalignedSpecLoc(),
"__unaligned");
11098 DS.ClearTypeQualifiers();
11100 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
11101 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
11102 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
11103 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
11104 DS.ClearTypeSpecType();
11111 bool FoundFunction =
false;
11117 diag::err_deduction_guide_with_complex_decl)
11121 if (!Chunk.Fun.hasTrailingReturnType()) {
11123 diag::err_deduction_guide_no_trailing_return_type);
11130 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11133 assert(TSI &&
"deduction guide has valid type but invalid return type?");
11134 bool AcceptableReturnType =
false;
11135 bool MightInstantiateToSpecialization =
false;
11138 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11139 bool TemplateMatches =
11141 auto TKind = SpecifiedName.
getKind();
11147 if (SimplyWritten && TemplateMatches)
11148 AcceptableReturnType =
true;
11153 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
11157 MightInstantiateToSpecialization =
true;
11160 if (!AcceptableReturnType) {
11162 diag::err_deduction_guide_bad_trailing_return_type)
11163 << GuidedTemplate << TSI->
getType()
11164 << MightInstantiateToSpecialization
11170 FoundFunction =
true;
11187 assert(*IsInline != PrevNS->
isInline());
11197 S.
Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
11200 S.
Diag(Loc, diag::err_inline_namespace_mismatch);
11218 bool IsInline = InlineLoc.
isValid();
11219 bool IsInvalid =
false;
11220 bool IsStd =
false;
11221 bool AddToKnown =
false;
11242 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
11246 if (IsInline != PrevNS->
isInline())
11248 &IsInline, PrevNS);
11249 }
else if (PrevDecl) {
11251 Diag(Loc, diag::err_redefinition_different_kind)
11256 }
else if (II->
isStr(
"std") &&
11262 AddToKnown = !IsInline;
11265 AddToKnown = !IsInline;
11279 if (PrevNS && IsInline != PrevNS->
isInline())
11281 &IsInline, PrevNS);
11293 if (
const VisibilityAttr *
Attr = Namespc->
getAttr<VisibilityAttr>())
11299 KnownNamespaces[Namespc] =
false;
11307 TU->setAnonymousNamespace(Namespc);
11309 cast<NamespaceDecl>(
Parent)->setAnonymousNamespace(Namespc);
11358 return AD->getNamespace();
11359 return dyn_cast_or_null<NamespaceDecl>(D);
11365 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
11366 assert(Namespc &&
"Invalid parameter, expected NamespaceDecl");
11369 if (Namespc->
hasAttr<VisibilityAttr>())
11372 if (DeferredExportedNamespaces.erase(Namespc))
11377 return cast_or_null<CXXRecordDecl>(
11386 return cast_or_null<NamespaceDecl>(
11398 Result.suppressDiagnostics();
11406 enum UnsupportedSTLSelect {
11413 struct InvalidSTLDiagnoser {
11418 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name =
"",
11419 const VarDecl *VD =
nullptr) {
11421 auto D = S.
Diag(Loc, diag::err_std_compare_type_not_supported)
11422 << TyForDiags << ((
int)Sel);
11423 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11424 assert(!Name.empty());
11428 if (Sel == USS_InvalidMember) {
11441 "Looking for comparison category type outside of C++.");
11454 if (Info && FullyCheckedComparisonCategories[
static_cast<unsigned>(
Kind)]) {
11467 Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11468 << NameForDiags << (
int)Usage;
11483 InvalidSTLDiagnoser UnsupportedSTLError{*
this, Loc, TyForDiags(Info)};
11486 return UnsupportedSTLError(USS_NonTrivial);
11491 if (
Base->isEmpty())
11494 return UnsupportedSTLError();
11503 !FIt->getType()->isIntegralOrEnumerationType()) {
11504 return UnsupportedSTLError();
11514 return UnsupportedSTLError(USS_MissingMember, MemName);
11517 assert(VD &&
"should not be null!");
11524 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11530 return UnsupportedSTLError();
11537 FullyCheckedComparisonCategories[
static_cast<unsigned>(
Kind)] =
true;
11559 "Looking for std::initializer_list outside of C++.");
11573 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11581 Template = dyn_cast_or_null<ClassTemplateDecl>(
11582 TST->getTemplateName().getAsTemplateDecl());
11583 Arguments = TST->template_arguments().begin();
11601 if (!isa<TemplateTypeParmDecl>(Params->
getParam(0)))
11613 *Element = Arguments[0].getAsType();
11620 S.
Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11627 S.
Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11632 Result.suppressDiagnostics();
11635 S.
Diag(Found->
getLocation(), diag::err_malformed_std_initializer_list);
11643 !isa<TemplateTypeParmDecl>(Params->
getParam(0))) {
11644 S.
Diag(Template->
getLocation(), diag::err_malformed_std_initializer_list);
11688 case Decl::TranslationUnit:
11690 case Decl::LinkageSpec:
11702 bool ValidateCandidate(
const TypoCorrection &candidate)
override {
11704 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
11708 std::unique_ptr<CorrectionCandidateCallback> clone()
override {
11709 return std::make_unique<NamespaceValidatorCCC>(*
this);
11720 NamespaceValidatorCCC CCC{};
11726 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
11727 Ident->
getName().equals(CorrectedStr);
11729 S.
PDiag(diag::err_using_directive_member_suggest)
11730 << Ident << DC << DroppedSpecifier << SS.
getRange(),
11731 S.
PDiag(diag::note_namespace_defined_here));
11734 S.
PDiag(diag::err_using_directive_suggest) << Ident,
11735 S.
PDiag(diag::note_namespace_defined_here));
11737 R.
addDecl(Corrected.getFoundDecl());
11748 assert(!SS.
isInvalid() &&
"Invalid CXXScopeSpec.");
11749 assert(NamespcName &&
"Invalid NamespcName.");
11750 assert(IdentLoc.
isValid() &&
"Invalid NamespceName location.");
11753 while (S->isTemplateParamScope())
11754 S = S->getParent();
11773 NamespcName->
isStr(
"std")) {
11774 Diag(IdentLoc, diag::ext_using_undefined_std);
11785 assert(NS &&
"expected namespace decl");
11804 CommonAncestor = CommonAncestor->
getParent();
11808 IdentLoc, Named, CommonAncestor);
11812 Diag(IdentLoc, diag::warn_using_directive_in_header);
11817 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.
getRange();
11848 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
11852 switch (Name.getKind()) {
11863 Diag(Name.getBeginLoc(),
11865 ? diag::warn_cxx98_compat_using_decl_constructor
11866 : diag::err_using_decl_constructor)
11874 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.
getRange();
11878 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
11879 <<
SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
11883 llvm_unreachable(
"cannot parse qualified deduction guide name");
11894 ? diag::err_access_decl
11895 : diag::warn_access_decl_deprecated)
11906 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
11914 SS, TargetNameInfo, EllipsisLoc, AttrList,
11928 assert(!SS->
isInvalid() &&
"ScopeSpec is invalid");
11938 ? diag::err_using_enum_is_dependent
11939 : diag::err_unknown_typename)
11945 auto *Enum = dyn_cast_if_present<EnumDecl>(EnumTy->
getAsTagDecl());
11947 Diag(IdentLoc, diag::err_using_enum_not_enum) << EnumTy;
11951 if (
auto *Def = Enum->getDefinition())
11954 if (TSI ==
nullptr)
11977 TD2->getUnderlyingType());
11981 if (isa<UnresolvedUsingIfExistsDecl>(D1) &&
11982 isa<UnresolvedUsingIfExistsDecl>(D2))
12014 if (
auto *Using = dyn_cast<UsingDecl>(BUD)) {
12018 if (isa<EnumDecl>(OrigDC))
12026 Diag(Using->getLocation(),
12027 diag::err_using_decl_nested_name_specifier_is_current_class)
12028 << Using->getQualifierLoc().getSourceRange();
12030 Using->setInvalidDecl();
12034 Diag(Using->getQualifierLoc().getBeginLoc(),
12035 diag::err_using_decl_nested_name_specifier_is_not_base_class)
12036 << Using->getQualifier() << cast<CXXRecordDecl>(
CurContext)
12037 << Using->getQualifierLoc().getSourceRange();
12039 Using->setInvalidDecl();
12044 if (
Previous.empty())
return false;
12047 if (isa<UsingShadowDecl>(
Target))
12048 Target = cast<UsingShadowDecl>(
Target)->getTargetDecl();
12055 NamedDecl *NonTag =
nullptr, *Tag =
nullptr;
12056 bool FoundEquivalentDecl =
false;
12059 NamedDecl *D = (*I)->getUnderlyingDecl();
12063 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D))
12066 if (
auto *RD = dyn_cast<CXXRecordDecl>(D)) {
12071 !isa<IndirectFieldDecl>(
Target) &&
12072 !isa<UnresolvedUsingValueDecl>(
Target) &&
12081 PrevShadow = Shadow;
12082 FoundEquivalentDecl =
true;
12086 FoundEquivalentDecl =
true;
12090 (isa<TagDecl>(D) ? Tag : NonTag) = D;
12093 if (FoundEquivalentDecl)
12098 if (isa<UnresolvedUsingIfExistsDecl>(
Target) !=
12099 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
12100 if (!NonTag && !Tag)
12103 Diag(
Target->getLocation(), diag::note_using_decl_target);
12104 Diag((NonTag ? NonTag : Tag)->getLocation(),
12105 diag::note_using_decl_conflict);
12134 Diag(
Target->getLocation(), diag::note_using_decl_target);
12142 if (isa<TagDecl>(
Target)) {
12144 if (!Tag)
return false;
12147 Diag(
Target->getLocation(), diag::note_using_decl_target);
12148 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
12154 if (!NonTag)
return false;
12157 Diag(
Target->getLocation(), diag::note_using_decl_target);
12167 for (
auto &B : Derived->
bases())
12168 if (B.getType()->getAsCXXRecordDecl() ==
Base)
12169 return B.isVirtual();
12170 llvm_unreachable(
"not a direct base class");
12179 if (isa<UsingShadowDecl>(
Target)) {
12180 Target = cast<UsingShadowDecl>(
Target)->getTargetDecl();
12181 assert(!isa<UsingShadowDecl>(
Target) &&
"nested shadow declaration");
12185 if (
auto *TargetTD = dyn_cast<TemplateDecl>(
Target))
12186 NonTemplateTarget = TargetTD->getTemplatedDecl();
12189 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
12190 UsingDecl *Using = cast<UsingDecl>(BUD);
12191 bool IsVirtualBase =
12193 Using->getQualifier()->getAsRecordDecl());
12247 cast<CXXRecordDecl>(Shadow->
getDeclContext())->removeConversion(Shadow);
12254 S->RemoveDecl(Shadow);
12268 bool &AnyDependentBases) {
12273 CanQualType BaseType =
Base.getType()->getCanonicalTypeUnqualified();
12274 if (CanonicalDesiredBase == BaseType)
12276 if (BaseType->isDependentType())
12277 AnyDependentBases =
true;
12285 UsingValidatorCCC(
bool HasTypenameKeyword,
bool IsInstantiation,
12287 : HasTypenameKeyword(HasTypenameKeyword),
12288 IsInstantiation(IsInstantiation), OldNNS(NNS),
12289 RequireMemberOf(RequireMemberOf) {}
12291 bool ValidateCandidate(
const TypoCorrection &Candidate)
override {
12295 if (!ND || isa<NamespaceDecl>(ND))
12305 if (RequireMemberOf) {
12306 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12307 if (FoundRecord && FoundRecord->isInjectedClassName()) {
12328 bool AnyDependentBases =
false;
12331 AnyDependentBases) &&
12332 !AnyDependentBases)
12336 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
12342 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12343 if (FoundRecord && FoundRecord->isInjectedClassName())
12347 if (isa<TypeDecl>(ND))
12348 return HasTypenameKeyword || !IsInstantiation;
12350 return !HasTypenameKeyword;
12353 std::unique_ptr<CorrectionCandidateCallback> clone()
override {
12354 return std::make_unique<UsingValidatorCCC>(*
this);
12358 bool HasTypenameKeyword;
12359 bool IsInstantiation;
12398 bool IsUsingIfExists) {
12399 assert(!SS.
isInvalid() &&
"Invalid CXXScopeSpec.");
12401 assert(IdentLoc.
isValid() &&
"Invalid TargetName location.");
12410 if (
auto *RD = dyn_cast<CXXRecordDecl>(
CurContext))
12423 assert(IsInstantiation &&
"no scope in non-instantiation");
12451 Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
12457 if (!LookupContext || EllipsisLoc.
isValid()) {
12461 SS, NameInfo, IdentLoc))
12464 if (HasTypenameKeyword) {
12467 UsingLoc, TypenameLoc,
12469 IdentLoc, NameInfo.
getName(),
12473 QualifierLoc, NameInfo, EllipsisLoc);
12481 auto Build = [&](
bool Invalid) {
12484 UsingName, HasTypenameKeyword);
12491 auto BuildInvalid = [&]{
return Build(
true); };
12492 auto BuildValid = [&]{
return Build(
false); };
12495 return BuildInvalid();
12504 if (!IsInstantiation)
12521 if (R.
empty() && IsUsingIfExists)
12538 isa<TranslationUnitDecl>(LookupContext) &&
12541 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.
getScopeRep(),
12549 << NameInfo.
getName() << LookupContext << 0
12554 NamedDecl *ND = Corrected.getCorrectionDecl();
12556 return BuildInvalid();
12559 auto *RD = dyn_cast<CXXRecordDecl>(ND);
12562 RD = cast<CXXRecordDecl>(RD->
getParent());
12565 if (Corrected.WillReplaceSpecifier()) {
12567 Builder.MakeTrivial(
Context, Corrected.getCorrectionSpecifier(),
12569 QualifierLoc = Builder.getWithLocInContext(
Context);
12574 auto *CurClass = cast<CXXRecordDecl>(
CurContext);
12588 Diag(IdentLoc, diag::err_no_member)
12590 return BuildInvalid();
12595 return BuildInvalid();
12597 if (HasTypenameKeyword) {
12601 Diag(IdentLoc, diag::err_using_typename_non_type);
12603 Diag((*I)->getUnderlyingDecl()->getLocation(),
12604 diag::note_using_decl_target);
12605 return BuildInvalid();
12612 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
12614 return BuildInvalid();
12621 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
12623 return BuildInvalid();
12653 bool Invalid =
false;
12665 if (UED->getEnumDecl() == ED) {
12666 Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
12705 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
12706 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
12707 isa<UsingPackDecl>(InstantiatedFrom));
12711 UPD->setAccess(InstantiatedFrom->
getAccess());
12718 assert(!UD->
hasTypename() &&
"expecting a constructor name");
12721 assert(SourceType &&
12722 "Using decl naming constructor doesn't have type in scope spec.");
12726 bool AnyDependentBases =
false;
12728 AnyDependentBases);
12729 if (!
Base && !AnyDependentBases) {
12731 diag::err_using_decl_constructor_not_in_direct_base)
12733 <<
QualType(SourceType, 0) << TargetClass;
12739 Base->setInheritConstructors();
12748 bool HasTypenameKeyword,
12767 if (Qual->
isDependent() && !HasTypenameKeyword) {
12768 for (
auto *D : Prev) {
12769 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
12770 bool OldCouldBeEnumerator =
12771 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
12773 OldCouldBeEnumerator ? diag::err_redefinition
12774 : diag::err_redefinition_different_kind)
12775 << Prev.getLookupName();
12791 if (
UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
12792 DTypename = UD->hasTypename();
12793 DQual = UD->getQualifier();
12795 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
12797 DQual = UD->getQualifier();
12799 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
12801 DQual = UD->getQualifier();
12806 if (HasTypenameKeyword != DTypename)
continue;
12814 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.
getRange();
12835 assert(
bool(NamedContext) == (R || UD) && !(R && UD) &&
12836 "resolvable context must have exactly one set of decls");
12840 bool Cxx20Enumerator =
false;
12841 if (NamedContext) {
12850 if (
auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
12854 if (EC && R && ED->isScoped())
12857 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
12858 : diag::ext_using_decl_scoped_enumerator)
12862 NamedContext = ED->getDeclContext();
12882 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
12883 : diag::err_using_decl_can_not_refer_to_class_member)
12886 if (Cxx20Enumerator)
12889 auto *RD = NamedContext
12901 Diag(SS.
getBeginLoc(), diag::note_using_decl_class_member_workaround)
12909 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
12925 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12940 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12950 if (!NamedContext) {
12966 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
12967 : diag::err_using_decl_nested_name_specifier_is_not_class)
12970 if (Cxx20Enumerator)
12987 cast<CXXRecordDecl>(NamedContext))) {
12989 if (Cxx20Enumerator) {
12990 Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
12997 diag::err_using_decl_nested_name_specifier_is_current_class)
13002 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
13004 diag::err_using_decl_nested_name_specifier_is_not_base_class)
13029 Bases.insert(
Base);
13034 if (!cast<CXXRecordDecl>(
CurContext)->forallBases(Collect))
13040 return !Bases.count(
Base);
13045 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
13046 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
13050 diag::err_using_decl_nested_name_specifier_is_not_base_class)
13064 while (S->isTemplateParamScope())
13065 S = S->getParent();
13067 "got alias-declaration outside of declaration scope");
13069 if (
Type.isInvalid())
13072 bool Invalid =
false;
13088 TemplateParamLists.size()
13095 Previous.getFoundDecl()->isTemplateParameter()) {
13101 "name in alias declaration must be an identifier");
13103 Name.StartLocation,
13104 Name.Identifier, TInfo);
13117 bool Redeclaration =
false;
13120 if (TemplateParamLists.size()) {
13124 if (TemplateParamLists.size() != 1) {
13125 Diag(UsingLoc, diag::err_alias_template_extra_headers)
13126 <<
SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13127 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13139 Redeclaration =
true;
13142 if (!OldDecl && !Invalid) {
13143 Diag(UsingLoc, diag::err_redefinition_different_kind)
13144 << Name.Identifier;
13158 OldTemplateParams =
13186 Name.Identifier, TemplateParams,
13194 else if (OldDecl) {
13201 if (
auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
13229 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.
getRange();
13261 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
13263 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
13264 << AD->getNamespace();
13269 ? diag::err_redefinition
13270 : diag::err_redefinition_different_kind;
13271 Diag(AliasLoc, DiagID) << Alias;
13292 struct SpecialMemberExceptionSpecInfo
13293 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
13301 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
13306 void visitClassSubobject(
CXXRecordDecl *Class, Subobject Subobj,
13309 void visitSubobjectCall(Subobject Subobj,
13319 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
13321 if (
auto *BaseCtor = SMOR.
getMethod()) {
13322 visitSubobjectCall(
Base, BaseCtor);
13326 visitClassSubobject(BaseClass,
Base, 0);
13330 bool SpecialMemberExceptionSpecInfo::visitField(
FieldDecl *FD) {
13341 ExceptSpec.CalledExpr(E);
13344 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
13350 void SpecialMemberExceptionSpecInfo::visitClassSubobject(
CXXRecordDecl *Class,
13354 bool IsMutable =
Field &&
Field->isMutable();
13355 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
13358 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
13363 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
13372 ExplicitSpec.
setKind(Result.getBoolValue()
13392 ComputingExceptionSpec CES(S, MD, Loc);
13399 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->
getLocation());
13401 return Info.ExceptSpec;
13408 diag::err_exception_spec_incomplete_type))
13409 return Info.ExceptSpec;
13426 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
13427 : Info.VisitAllBases);
13429 return Info.ExceptSpec;
13434 struct DeclaringSpecialMember {
13438 bool WasAlreadyBeingDeclared;
13441 : S(S), D(RD, CSM), SavedContext(S, RD) {
13443 if (WasAlreadyBeingDeclared)
13464 ~DeclaringSpecialMember() {
13465 if (!WasAlreadyBeingDeclared) {
13472 bool isAlreadyBeingDeclared()
const {
13473 return WasAlreadyBeingDeclared;
13494 void Sema::setupImplicitSpecialMemberType(
CXXMethodDecl *SpecialMem,
13512 cast<CXXRecordDecl>(SpecialMem->
getParent())->isLambda()) {
13528 "Should not build implicit default constructor!");
13531 if (DSM.isAlreadyBeingDeclared())
13555 setupImplicitSpecialMemberType(DefaultCon,
Context.
VoidTy, std::nullopt);
13578 ClassDecl->
addDecl(DefaultCon);
13585 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
13586 !Constructor->doesThisDeclarationHaveABody() &&
13587 !Constructor->isDeleted()) &&
13588 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
13589 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13593 assert(ClassDecl &&
"DefineImplicitDefaultConstructor - invalid constructor");
13604 Scope.addContextNote(CurrentLocation);
13607 Constructor->setInvalidDecl();
13612 ? Constructor->getEndLoc()
13613 : Constructor->getLocation();
13615 Constructor->markUsed(
Context);
13618 L->CompletedImplicitDefinition(Constructor);
13621 DiagnoseUninitializedFields(*
this, Constructor);
13647 ->getInheritedConstructor()
13650 return cast<CXXConstructorDecl>(Ctor);
13665 false, BaseCtor, &ICI);
13682 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
13688 for (
unsigned I = 0, N = FPT->
getNumParams(); I != N; ++I) {
13692 Context, DerivedCtor, UsingLoc, UsingLoc,
nullptr,
13699 ParamDecls.push_back(PD);
13704 assert(!BaseCtor->
isDeleted() &&
"should not use deleted constructor");
13707 Derived->
addDecl(DerivedCtor);
13712 return DerivedCtor;
13725 assert(Constructor->getInheritedConstructor() &&
13726 !Constructor->doesThisDeclarationHaveABody() &&
13727 !Constructor->isDeleted());
13728 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13742 Scope.addContextNote(CurrentLocation);
13745 Constructor->getInheritedConstructor().getShadowDecl();
13747 Constructor->getInheritedConstructor().getConstructor();
13761 for (
bool VBase : {
false,
true}) {
13763 if (B.isVirtual() != VBase)
13766 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
13771 if (!BaseCtor.first)
13776 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
13780 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
13789 Constructor->setInvalidDecl();
13794 Constructor->markUsed(
Context);
13797 L->CompletedImplicitDefinition(Constructor);
13800 DiagnoseUninitializedFields(*
this, Constructor);
13810 DeclaringSpecialMember DSM(*
this, ClassDecl,
CXXDestructor);
13811 if (DSM.isAlreadyBeingDeclared())
13833 Destructor->setDefaulted();
13835 setupImplicitSpecialMemberType(Destructor,
Context.
VoidTy, std::nullopt);
13846 Destructor->setTrivialForCall(ClassDecl->
hasAttr<TrivialABIAttr>() ||
13865 ClassDecl->
addDecl(Destructor);
13872 assert((Destructor->isDefaulted() &&
13873 !Destructor->doesThisDeclarationHaveABody() &&
13874 !Destructor->isDeleted()) &&
13875 "DefineImplicitDestructor - call it for implicit default dtor");
13876 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
13880 assert(ClassDecl &&
"DefineImplicitDestructor - invalid destructor");
13891 Scope.addContextNote(CurrentLocation);
13894 Destructor->getParent());
13897 Destructor->setInvalidDecl();
13902 ? Destructor->getEndLoc()
13903 : Destructor->getLocation();
13905 Destructor->markUsed(
Context);
13908 L->CompletedImplicitDefinition(Destructor);
13914 if (Destructor->isInvalidDecl())
13919 "implicit complete dtors unneeded outside MS ABI");
13921 "complete dtor only exists for classes with vbases");
13926 Scope.addContextNote(CurrentLocation);
13957 if (M->getParent()->getTemplateSpecializationKind() !=
13977 "adjusting dtor exception specs was introduced in c++11");
13979 if (Destructor->isDependentContext())
13987 if (DtorType->hasExceptionSpec())
13996 Destructor->setType(
14010 class ExprBuilder {
14011 ExprBuilder(
const ExprBuilder&) =
delete;
14012 ExprBuilder &operator=(
const ExprBuilder&) =
delete;
14015 static Expr *assertNotNull(
Expr *E) {
14016 assert(E &&
"Expression construction must not fail.");
14022 virtual ~ExprBuilder() {}
14027 class RefBuilder:
public ExprBuilder {
14037 : Var(Var), VarType(VarType) {}
14040 class ThisBuilder:
public ExprBuilder {
14047 class CastBuilder:
public ExprBuilder {
14048 const ExprBuilder &Builder;
14056 CK_UncheckedDerivedToBase,
Kind,
14065 class DerefBuilder:
public ExprBuilder {
14066 const ExprBuilder &Builder;
14070 return assertNotNull(
14074 DerefBuilder(
const ExprBuilder &Builder) : Builder(Builder) {}
14077 class MemberBuilder:
public ExprBuilder {
14078 const ExprBuilder &Builder;
14088 nullptr, MemberLookup,
nullptr,
nullptr).get());
14091 MemberBuilder(
const ExprBuilder &Builder,
QualType Type,
bool IsArrow,
14093 : Builder(Builder),
Type(
Type), IsArrow(IsArrow),
14094 MemberLookup(MemberLookup) {}
14097 class MoveCastBuilder:
public ExprBuilder {
14098 const ExprBuilder &Builder;
14102 return assertNotNull(
CastForMoving(S, Builder.build(S, Loc)));
14105 MoveCastBuilder(
const ExprBuilder &Builder) : Builder(Builder) {}
14108 class LvalueConvBuilder:
public ExprBuilder {
14109 const ExprBuilder &Builder;
14113 return assertNotNull(
14117 LvalueConvBuilder(
const ExprBuilder &Builder) : Builder(Builder) {}
14120 class SubscriptBuilder:
public ExprBuilder {
14121 const ExprBuilder &
Base;
14122 const ExprBuilder &Index;
14127 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).
get());
14130 SubscriptBuilder(
const ExprBuilder &
Base,
const ExprBuilder &Index)
14142 const ExprBuilder &ToB,
const ExprBuilder &FromB) {
14151 Expr *From = FromB.build(S, Loc);
14155 Expr *To = ToB.build(S, Loc);
14161 bool NeedsCollectableMemCpy =
14166 StringRef MemCpyName = NeedsCollectableMemCpy ?
14167 "__builtin_objc_memmove_collectable" :
14168 "__builtin_memcpy";
14181 assert(MemCpyRef.
isUsable() &&
"Builtin reference cannot fail");
14183 Expr *CallArgs[] = {
14187 Loc, CallArgs, Loc);
14189 assert(!Call.isInvalid() &&
"Call to __builtin_memcpy cannot fail!");
14190 return Call.getAs<
Stmt>();
14222 const ExprBuilder &To,
const ExprBuilder &From,
14223 bool CopyingBaseSubobject,
bool Copying,
14224 unsigned Depth = 0) {
14240 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
14275 if (CopyingBaseSubobject) {
14306 Expr *FromInst = From.build(S, Loc);
14309 Loc, FromInst, Loc);
14310 if (Call.isInvalid())
14329 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
14349 llvm::raw_svector_ostream OS(Str);
14350 OS <<
"__i" <<
Depth;
14354 IterationVarName, SizeType,
14363 RefBuilder IterationVarRef(IterationVar, SizeType);
14364 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
14370 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
14371 MoveCastBuilder FromIndexMove(FromIndexCopy);
14372 const ExprBuilder *FromIndex;
14374 FromIndex = &FromIndexCopy;
14376 FromIndex = &FromIndexMove;
14378 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
14383 ToIndex, *FromIndex, CopyingBaseSubobject,
14384 Copying,
Depth + 1);
14386 if (Copy.isInvalid() || !Copy.get())
14393 S.
Context, IterationVarRefRVal.build(S, Loc),
14407 Loc, Loc, InitStmt,
14414 const ExprBuilder &To,
const ExprBuilder &From,
14415 bool CopyingBaseSubobject,
bool Copying) {
14422 CopyingBaseSubobject,
14427 if (!Result.isInvalid() && !Result.get())
14441 if (DSM.isAlreadyBeingDeclared())
14476 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
14486 ClassLoc, ClassLoc,
14510 ClassDecl->
addDecl(CopyAssignment);
14512 return CopyAssignment;
14526 }
else if (!isa<CXXConstructorDecl>(CopyOp) &&
14529 for (
auto *I : RD->
ctors()) {
14530 if (I->isCopyConstructor()) {
14531 UserDeclaredOperation = I;
14535 assert(UserDeclaredOperation);
14536 }
else if (isa<CXXConstructorDecl>(CopyOp) &&
14539 for (
auto *I : RD->
methods()) {
14540 if (I->isCopyAssignmentOperator()) {
14541 UserDeclaredOperation = I;
14545 assert(UserDeclaredOperation);
14548 if (UserDeclaredOperation) {
14549 bool UDOIsUserProvided = UserDeclaredOperation->
isUserProvided();
14550 bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
14551 bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
14553 (UDOIsUserProvided && UDOIsDestructor)
14554 ? diag::warn_deprecated_copy_with_user_provided_dtor
14555 : (UDOIsUserProvided && !UDOIsDestructor)
14556 ? diag::warn_deprecated_copy_with_user_provided_copy
14557 : (!UDOIsUserProvided && UDOIsDestructor)
14558 ? diag::warn_deprecated_copy_with_dtor
14559 : diag::warn_deprecated_copy;
14561 << RD << IsCopyAssignment;
14572 "DefineImplicitCopyAssignment called for wrong function");
14590 Scope.addContextNote(CurrentLocation);
14612 Qualifiers OtherQuals = Other->getType().getQualifiers();
14613 QualType OtherRefType = Other->getType();
14626 RefBuilder OtherRef(Other, OtherRefType);
14632 bool Invalid =
false;
14633 for (
auto &
Base : ClassDecl->
bases()) {
14636 QualType BaseType =
Base.getType().getUnqualifiedType();
14643 BasePath.push_back(&
Base);
14651 DerefBuilder DerefThis(
This);
14652 CastBuilder To(DerefThis,
14668 Statements.push_back(Copy.
getAs<
Expr>());
14672 for (
auto *Field : ClassDecl->
fields()) {
14675 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14678 if (Field->isInvalidDecl()) {
14684 if (Field->getType()->isReferenceType()) {
14685 Diag(ClassDecl->
getLocation(), diag::err_uninitialized_member_for_assign)
14687 Diag(Field->getLocation(), diag::note_declared_at);
14695 Diag(ClassDecl->
getLocation(), diag::err_uninitialized_member_for_assign)
14697 Diag(Field->getLocation(), diag::note_declared_at);
14703 if (Field->isZeroLengthBitField(
Context))
14706 QualType FieldType = Field->getType().getNonReferenceType();
14709 "Incomplete array type is not valid");
14715 LookupResult MemberLookup(*
this, Field->getDeclName(), Loc,
14720 MemberBuilder From(OtherRef, OtherRefType,
false, MemberLookup);
14736 Statements.push_back(Copy.
getAs<
Stmt>());
14741 Expr *ThisExpr =
nullptr;
14745 ThisExpr = ThisObj.
get();
14747 ThisExpr =
This.build(*
this, Loc);
14754 Statements.push_back(Return.
getAs<
Stmt>());
14767 assert(!Body.
isInvalid() &&
"Compound statement creation cannot fail");
14773 L->CompletedImplicitDefinition(CopyAssignOperator);
14781 if (DSM.isAlreadyBeingDeclared())
14815 setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
14825 ClassLoc, ClassLoc,
14849 ClassDecl->
addDecl(MoveAssignment);
14851 return MoveAssignment;
14859 assert(!Class->isDependentContext() &&
"should not define dependent move");
14865 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
14866 Class->getNumBases() < 2)
14870 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
14873 for (
auto &BI : Class->bases()) {
14874 Worklist.push_back(&BI);
14875 while (!Worklist.empty()) {
14881 if (!
Base->hasNonTrivialMoveAssignment())
14906 VBases.insert(std::make_pair(
Base->getCanonicalDecl(), &BI))
14908 if (Existing && Existing != &BI) {
14909 S.
Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
14912 << (
Base->getCanonicalDecl() ==
14915 S.
Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
14916 << (
Base->getCanonicalDecl() ==
14917 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14921 Existing =
nullptr;
14931 llvm::append_range(Worklist, llvm::make_pointer_range(
Base->bases()));
14944 "DefineImplicitMoveAssignment called for wrong function");
14974 Scope.addContextNote(CurrentLocation);
14990 RefBuilder OtherRef(Other, OtherRefType);
14992 MoveCastBuilder MoveOther(OtherRef);
14998 bool Invalid =
false;
14999 for (
auto &
Base : ClassDecl->
bases()) {
15010 QualType BaseType =
Base.getType().getUnqualifiedType();
15017 BasePath.push_back(&
Base);
15021 CastBuilder From(OtherRef, BaseType,
VK_XValue, BasePath);
15024 DerefBuilder DerefThis(
This);
15027 CastBuilder To(DerefThis,
15037 if (
Move.isInvalid()) {
15043 Statements.push_back(
Move.getAs<
Expr>());
15047 for (
auto *Field : ClassDecl->
fields()) {
15050 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
15053 if (Field->isInvalidDecl()) {
15059 if (Field->getType()->isReferenceType()) {
15060 Diag(ClassDecl->
getLocation(), diag::err_uninitialized_member_for_assign)
15062 Diag(Field->getLocation(), diag::note_declared_at);
15070 Diag(ClassDecl->
getLocation(), diag::err_uninitialized_member_for_assign)
15072 Diag(Field->getLocation(), diag::note_declared_at);
15078 if (Field->isZeroLengthBitField(
Context))
15081 QualType FieldType = Field->getType().getNonReferenceType();
15084 "Incomplete array type is not valid");
15089 LookupResult MemberLookup(*
this, Field->getDeclName(), Loc,
15093 MemberBuilder From(MoveOther, OtherRefType,
15094 false, MemberLookup);
15096 true, MemberLookup);
15098 assert(!From.build(*
this, Loc)->isLValue() &&
15099 "Member reference with rvalue base must be rvalue except for reference "
15100 "members, which aren't allowed for move assignment.");
15107 if (
Move.isInvalid()) {
15113 Statements.push_back(
Move.getAs<
Stmt>());
15125 Statements.push_back(Return.
getAs<
Stmt>());
15138 assert(!Body.
isInvalid() &&
"Compound statement creation cannot fail");
15144 L->CompletedImplicitDefinition(MoveAssignOperator);
15156 if (DSM.isAlreadyBeingDeclared())
15194 setupImplicitSpecialMemberType(CopyConstructor,
Context.
VoidTy, ArgType);
15222 ClassDecl->
hasAttr<TrivialABIAttr>() ||
15241 ClassDecl->
addDecl(CopyConstructor);
15243 return CopyConstructor;
15252 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
15257 assert(ClassDecl &&
"DefineImplicitCopyConstructor - invalid constructor");
15268 Scope.addContextNote(CurrentLocation);
15291 L->CompletedImplicitDefinition(CopyConstructor);
15300 if (DSM.isAlreadyBeingDeclared())
15335 setupImplicitSpecialMemberType(MoveConstructor,
Context.
VoidTy, ArgType);
15345 ClassLoc, ClassLoc,
15357 ClassDecl->
hasAttr<TrivialABIAttr>() ||
15376 ClassDecl->
addDecl(MoveConstructor);
15378 return MoveConstructor;
15387 "DefineImplicitMoveConstructor - call it for implicit move ctor");
15392 assert(ClassDecl &&
"DefineImplicitMoveConstructor - invalid constructor");
15403 Scope.addContextNote(CurrentLocation);
15419 L->CompletedImplicitDefinition(MoveConstructor);
15448 if (CallOp != Invoker) {
15467 if (Invoker != CallOp) {
15480 assert(FunctionRef &&
"Can't refer to __invoke function?");
15488 L->CompletedImplicitDefinition(Conv);
15489 if (Invoker != CallOp)
15490 L->CompletedImplicitDefinition(Invoker);
15518 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15527 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15533 Stmt *ReturnS = Return.
get();
15540 L->CompletedImplicitDefinition(Conv);
15547 switch (Args.size()) {
15552 if (!Args[1]->isDefaultArgument())
15557 return !Args[0]->isDefaultArgument();
15568 bool HadMultipleCandidates,
15569 bool IsListInitialization,
15570 bool IsStdInitListInitialization,
15571 bool RequiresZeroInit,
15572 unsigned ConstructKind,
15574 bool Elidable =
false;
15593 Expr *SubExpr = ExprArgs[0];
15603 FoundDecl, Constructor,
15604 Elidable, ExprArgs, HadMultipleCandidates,
15605 IsListInitialization,
15606 IsStdInitListInitialization, RequiresZeroInit,
15607 ConstructKind, ParenRange);
15616 bool HadMultipleCandidates,
15617 bool IsListInitialization,
15618 bool IsStdInitListInitialization,
15619 bool RequiresZeroInit,
15620 unsigned ConstructKind,
15622 if (
auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
15632 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
15633 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
15634 RequiresZeroInit, ConstructKind, ParenRange);
15644 bool HadMultipleCandidates,
15645 bool IsListInitialization,
15646 bool IsStdInitListInitialization,
15647 bool RequiresZeroInit,
15648 unsigned ConstructKind,
15651 Constructor->getParent(),
15653 "given constructor for wrong type");
15663 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
15664 HadMultipleCandidates, IsListInitialization,
15665 IsStdInitListInitialization, RequiresZeroInit,
15694 PDiag(diag::err_access_dtor_var)
15699 if (Destructor->isTrivial())
return;
15703 if (Destructor->isConstexpr()) {
15704 bool HasConstantInit =
false;
15711 diag::err_constexpr_var_requires_const_destruction) << VD;
15712 for (
unsigned I = 0, N = Notes.size(); I != N; ++I)
15713 Diag(Notes[I].first, Notes[I].second);
15737 bool AllowExplicit,
15738 bool IsListInitialization) {
15740 unsigned NumArgs = ArgsPtr.size();
15741 Expr **Args = ArgsPtr.data();
15747 if (NumArgs < NumParams)
15748 ConvertedArgs.reserve(NumParams);
15750 ConvertedArgs.reserve(NumArgs);
15756 Loc, Constructor, Proto, 0,
llvm::ArrayRef(Args, NumArgs), AllArgs,
15757 CallType, AllowExplicit, IsListInitialization);
15758 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
15762 CheckConstructorCall(Constructor, DeclInitType,
15773 if (isa<NamespaceDecl>(DC)) {
15775 diag::err_operator_new_delete_declared_in_namespace)
15779 if (isa<TranslationUnitDecl>(DC) &&
15782 diag::err_operator_new_delete_declared_static)
15794 return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType(
15802 unsigned DependentParamTypeDiag,
15803 unsigned InvalidParamTypeDiag) {
15821 return SemaRef.
Diag(
15824 ? diag::err_operator_new_delete_dependent_result_type
15825 : diag::err_operator_new_delete_invalid_result_type)
15832 diag::err_operator_new_delete_template_too_few_parameters)
15838 diag::err_operator_new_delete_too_few_parameters)
15845 if (
const auto *PtrTy =
15850 ExpectedFirstParamType =
15856 ExpectedFirstParamType) {
15861 ? DependentParamTypeDiag
15862 : InvalidParamTypeDiag)
15863 << FnDecl->
getDeclName() << ExpectedFirstParamType;
15886 diag::err_operator_new_dependent_param_type,
15887 diag::err_operator_new_param_type))
15894 diag::err_operator_new_default_arg)
15909 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
15924 SemaRef, FnDecl, SemaRef.
Context.
VoidTy, ExpectedFirstParamType,
15925 diag::err_operator_delete_dependent_param_type,
15926 diag::err_operator_delete_param_type))
15935 diag::err_destroying_operator_delete_not_usual);
15947 "Expected an overloaded operator declaration");
15957 if (Op == OO_Delete || Op == OO_Array_Delete)
15960 if (Op == OO_New || Op == OO_Array_New)
15970 if (
CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
15971 if (MethodDecl->isStatic()) {
15972 if (Op == OO_Call || Op == OO_Subscript)
15975 ? diag::warn_cxx20_compat_operator_overload_static
15976 : diag::ext_operator_overload_static))
15979 return Diag(FnDecl->
getLocation(), diag::err_operator_overload_static)
15983 bool ClassOrEnumParam =
false;
15985 QualType ParamType = Param->getType().getNonReferenceType();
15988 ClassOrEnumParam =
true;
15993 if (!ClassOrEnumParam)
15995 diag::err_operator_overload_needs_class_or_enum)
16005 if (Op != OO_Call) {
16008 if (Param->hasDefaultArg()) {
16009 FirstDefaultedParam = Param;
16013 if (FirstDefaultedParam) {
16014 if (Op == OO_Subscript) {
16016 ? diag::ext_subscript_overload
16017 : diag::error_subscript_overload)
16022 diag::err_operator_overload_default_arg)
16030 {
false,
false,
false }
16031 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
16032 , { Unary, Binary, MemberOnly }
16033 #include "clang/Basic/OperatorKinds.def"
16036 bool CanBeUnaryOperator = OperatorUses[Op][0];
16037 bool CanBeBinaryOperator = OperatorUses[Op][1];
16038 bool MustBeMemberOperator = OperatorUses[Op][2];
16045 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
16046 if (Op != OO_Call && Op != OO_Subscript &&
16047 ((NumParams == 1 && !CanBeUnaryOperator) ||
16048 (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
16049 (NumParams > 2))) {
16051 unsigned ErrorKind;
16052 if (CanBeUnaryOperator && CanBeBinaryOperator) {
16054 }
else if (CanBeUnaryOperator) {
16057 assert(CanBeBinaryOperator &&
16058 "All non-call overloaded operators are unary or binary!");
16061 return Diag(FnDecl->
getLocation(), diag::err_operator_overload_must_be)
16062 << FnDecl->
getDeclName() << NumParams << ErrorKind;
16065 if (Op == OO_Subscript && NumParams != 2) {
16067 ? diag::ext_subscript_overload
16068 : diag::error_subscript_overload)
16069 << FnDecl->
getDeclName() << (NumParams == 1 ? 0 : 2);
16074 if (Op != OO_Call &&
16076 return Diag(FnDecl->
getLocation(), diag::err_operator_overload_variadic)
16081 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
16083 diag::err_operator_overload_must_be_member)
16097 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
16104 diag::err_operator_overload_post_incdec_must_be_int)
16105 << LastParam->
getType() << (Op == OO_MinusMinus);
16117 if (TemplateParams->
size() == 1) {
16119 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->
getParam(0));
16133 if (SemaRef.
getLangOpts().CPlusPlus20 && PmDecl &&
16138 }
else if (TemplateParams->
size() == 2) {
16140 dyn_cast<TemplateTypeParmDecl>(TemplateParams->
getParam(0));
16142 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->
getParam(1));
16154 diag::ext_string_literal_operator_template);
16161 diag::err_literal_operator_template)
16170 if (isa<CXXMethodDecl>(FnDecl)) {
16171 Diag(FnDecl->
getLocation(), diag::err_literal_operator_outside_namespace)
16180 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
16199 diag::err_literal_operator_template_with_params);
16228 diag::err_literal_operator_param)
16245 diag::err_literal_operator_invalid_param)
16255 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
16262 Diag((*Param)->getSourceRange().getBegin(),
16263 diag::err_literal_operator_param)
16264 << FirstParamType <<
"'const char *'" << (*Param)->getSourceRange();
16271 Diag((*Param)->getSourceRange().getBegin(),
16272 diag::err_literal_operator_param)
16273 << FirstParamType <<
"'const char *'" << (*Param)->getSourceRange();
16286 Diag((*Param)->getSourceRange().getBegin(),
16287 diag::err_literal_operator_param)
16288 << FirstParamType <<
"'const char *'" << (*Param)->getSourceRange();
16296 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
16298 Diag((*Param)->getSourceRange().getBegin(),
16299 diag::err_literal_operator_param)
16301 << (*Param)->getSourceRange();
16305 Diag(FnDecl->
getLocation(), diag::err_literal_operator_bad_param_count);
16314 if (Param->hasDefaultArg()) {
16315 Diag(Param->getDefaultArgRange().getBegin(),
16316 diag::err_literal_operator_default_argument)
16317 << Param->getDefaultArgRange();
16322 StringRef LiteralName
16324 if (LiteralName[0] !=
'_' &&
16347 Diag(LangStr->
getExprLoc(), diag::err_language_linkage_spec_not_ascii)
16356 else if (
Lang ==
"C++")
16359 Diag(LangStr->
getExprLoc(), diag::err_language_linkage_spec_unknown)
16379 if (
getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
16381 PushGlobalModuleFragment(ExternLoc,
true);
16413 PopGlobalModuleFragment();
16416 return LinkageSpec;
16439 bool Invalid =
false;
16453 Diag(Loc, diag::err_catch_rvalue_ref);
16458 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
16464 unsigned DK = diag::err_catch_incomplete;
16468 DK = diag::err_catch_incomplete_ptr;
16471 BaseType = Ref->getPointeeType();
16473 DK = diag::err_catch_incomplete_ref;
16475 if (!Invalid && (Mode == 0 || !BaseType->
isVoidType()) &&
16480 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
16486 diag::err_abstract_type_in_decl,
16498 Diag(Loc, diag::err_objc_object_catch);
16503 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
16537 Expr *opaqueValue =
16585 assert(!S->isDeclScope(PrevDecl));
16589 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
16591 }
else if (PrevDecl->isTemplateParameter())
16619 Expr *AssertMessageExpr,
16622 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) :
nullptr;
16628 AssertMessage, RParenLoc,
false);
16638 switch (
V.getKind()) {
16639 case APValue::ValueKind::Int:
16644 int64_t BoolValue =
V.getInt().getExtValue();
16645 assert((BoolValue == 0 || BoolValue == 1) &&
16646 "Bool type, but value is not 0 or 1");
16647 llvm::raw_svector_ostream OS(Str);
16648 OS << (BoolValue ?
"true" :
"false");
16651 Str.push_back(
'\'');
16652 Str.push_back(
V.getInt().getExtValue());
16653 Str.push_back(
'\'');
16655 V.getInt().toString(Str);
16660 V.getFloat().toString(Str);
16663 case APValue::ValueKind::LValue:
16664 if (
V.isNullPointer()) {
16665 llvm::raw_svector_ostream OS(Str);
16671 case APValue::ValueKind::ComplexFloat: {
16672 llvm::raw_svector_ostream OS(Str);
16674 V.getComplexFloatReal().toString(Str);
16676 V.getComplexFloatImag().toString(Str);
16680 case APValue::ValueKind::ComplexInt: {
16681 llvm::raw_svector_ostream OS(Str);
16683 V.getComplexIntReal().toString(Str);
16685 V.getComplexIntImag().toString(Str);
16708 if (isa<SubstNonTypeTemplateParmExpr>(E))
16712 if (
const auto *UnaryOp = dyn_cast<UnaryOperator>(E))
16717 if (isa<BinaryOperator>(E))
16726 if (
const auto *Op = dyn_cast<BinaryOperator>(E)) {
16727 const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
16728 const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
16746 for (
unsigned I = 0; I < 2; I++) {
16747 const Expr *Side = DiagSide[I].Cond;
16752 DiagSide[I].Result.Val, Side->
getType(), DiagSide[I].ValueString);
16754 if (DiagSide[0].Print && DiagSide[1].Print) {
16755 Diag(Op->getExprLoc(), diag::note_expr_evaluates_to)
16756 << DiagSide[0].ValueString << Op->getOpcodeStr()
16757 << DiagSide[1].ValueString << Op->getSourceRange();
16767 assert(AssertExpr !=
nullptr &&
"Expected non-null condition");
16783 AssertExpr = FullAssertExpr.
get();
16786 Expr *BaseExpr = AssertExpr;
16798 diag::err_static_assert_expression_is_not_constant,
16802 if (!Failed && !Cond) {
16804 llvm::raw_svector_ostream Msg(MsgBuffer);
16805 if (AssertMessage) {
16806 const auto *MsgStr = cast<StringLiteral>(AssertMessage);
16807 if (MsgStr->isOrdinary())
16808 Msg << MsgStr->getString();
16813 Expr *InnerCond =
nullptr;
16815 std::tie(InnerCond, InnerCondDescription) =
16817 if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
16820 Diag(StaticAssertLoc, diag::err_static_assert_failed)
16825 }
else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
16826 && !isa<IntegerLiteral>(InnerCond)) {
16827 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
16828 << InnerCondDescription << !AssertMessage
16832 Diag(StaticAssertLoc, diag::err_static_assert_failed)
16844 AssertExpr = FullAssertExpr.
get();
16848 AssertExpr, AssertMessage, RParenLoc,
16861 assert(TSInfo &&
"NULL TypeSourceInfo for friend type declaration");
16887 diag::warn_cxx98_compat_unelaborated_friend_type :
16888 diag::ext_unelaborated_friend_type)
16896 diag::warn_cxx98_compat_nonclass_type_friend :
16897 diag::ext_nonclass_type_friend)
16904 diag::warn_cxx98_compat_enum_friend :
16905 diag::ext_enum_friend)
16917 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
16936 bool IsMemberSpecialization =
false;
16937 bool Invalid =
false;
16941 TagLoc, NameLoc, SS,
nullptr, TempParamLists,
true,
16942 IsMemberSpecialization, Invalid)) {
16943 if (TemplateParams->size() > 0) {
16951 FriendLoc, TempParamLists.size() - 1,
16952 TempParamLists.data()).
get();
16955 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16957 IsMemberSpecialization =
true;
16961 if (Invalid)
return true;
16963 bool isAllExplicitSpecializations =
true;
16964 for (
unsigned I = TempParamLists.size(); I-- > 0; ) {
16965 if (TempParamLists[I]->size()) {
16966 isAllExplicitSpecializations =
false;
16976 if (isAllExplicitSpecializations) {
16978 bool Owned =
false;
16979 bool IsDependent =
false;
17000 if (isa<DependentNameType>(T)) {
17014 TSI, FriendLoc, TempParamLists);
17020 assert(SS.
isNotEmpty() &&
"valid templated tag with no SS and no direct?");
17027 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
17038 TSI, FriendLoc, TempParamLists);
17120 Diag(Loc, diag::err_tagless_friend_type_template)
17137 if (!TempParams.empty())
17175 Diag(Loc, diag::err_unexpected_friend);
17210 Scope *DCScope = S;
17220 (FunctionContainingLocalClass =
17221 cast<CXXRecordDecl>(
CurContext)->isLocalClass())) {
17233 DCScope = S->getFnParent();
17243 DC =
Previous.getRepresentativeDecl()->getDeclContext();
17247 DC = FunctionContainingLocalClass;
17269 bool isTemplateId =
17294 if (isTemplateId) {
17295 if (isa<TranslationUnitDecl>(LookupDC))
break;
17309 if (!DC)
return nullptr;
17320 diag::warn_cxx98_compat_friend_is_member :
17321 diag::err_friend_is_member);
17357 assert(isa<CXXRecordDecl>(DC) &&
"friend declaration not in class?");
17384 if (DiagArg >= 0) {
17385 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
17396 DCScope = &FakeDCScope;
17399 bool AddToScope =
true;
17401 TemplateParams, AddToScope);
17402 if (!ND)
return nullptr;
17436 FD = FTD->getTemplatedDecl();
17438 FD = cast<FunctionDecl>(ND);
17449 Diag(FD->
getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
17451 diag::note_previous_declaration);
17453 Diag(FD->
getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
17458 Diag(FD->
getLocation(), diag::warn_template_qualified_friend_unsupported)
17473 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
17475 Diag(DelLoc, diag::err_deleted_non_function);
17486 Prev->getPreviousDecl()) &&
17487 !Prev->isDefined()) {
17488 Diag(DelLoc, diag::err_deleted_decl_not_first);
17489 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
17490 Prev->isImplicit() ? diag::note_previous_implicit_declaration
17491 : diag::note_previous_declaration);
17514 Diag(DelLoc, diag::err_deleted_main);
17526 auto *FD = dyn_cast<FunctionDecl>(Dcl);
17528 if (
auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
17530 Diag(DefaultLoc, diag::err_defaulted_comparison_template);
17535 Diag(DefaultLoc, diag::err_default_special_members)
17546 (!FD->isDependentContext() ||
17547 (!isa<CXXConstructorDecl>(FD) &&
17549 Diag(DefaultLoc, diag::err_default_special_members)
17559 ? diag::warn_cxx17_compat_defaulted_comparison
17560 : diag::ext_defaulted_comparison);
17563 FD->setDefaulted();
17564 FD->setExplicitlyDefaulted();
17565 FD->setDefaultLoc(DefaultLoc);
17568 if (FD->isDependentContext())
17574 FD->setWillHaveBody(
false);
17587 if (isa<CXXMethodDecl>(FD)) {
17589 if (
const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
17603 auto *MD = cast<CXXMethodDecl>(FD);
17614 for (
Stmt *SubStmt : S->children()) {
17617 if (isa<ReturnStmt>(SubStmt))
17618 Self.
Diag(SubStmt->getBeginLoc(),
17619 diag::err_return_in_constructor_handler);
17620 if (!isa<Expr>(SubStmt))
17626 for (
unsigned I = 0, E = TryBlock->
getNumHandlers(); I != E; ++I) {
17634 switch (BodyKind) {
17643 "Parsed function body should be '= delete;' or '= default;'");
17653 for (
unsigned I = 0, E = OldFT->
getNumParams(); I != E; ++I)
17657 !NewFT->getExtParameterInfo(I).isNoEscape()) {
17659 diag::warn_overriding_method_missing_noescape);
17661 diag::note_overridden_marked_noescape);
17666 const auto *OldCSA = Old->
getAttr<CodeSegAttr>();
17667 const auto *NewCSA = New->
getAttr<CodeSegAttr>();
17668 if ((NewCSA || OldCSA) &&
17669 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
17678 if (NewCC == OldCC)
17689 diag::err_conflicting_overriding_cc_attributes)
17715 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
17723 if (NewClassTy.
isNull()) {
17725 diag::err_different_return_type_for_overriding_virtual_function)
17741 if (!RT->isBeingDefined() &&
17743 diag::err_covariant_return_incomplete,
17760 NewClassTy, OldClassTy,
17761 diag::err_covariant_return_inaccessible_base,
17762 diag::err_covariant_return_ambiguous_derived_to_base_conv,
17778 diag::err_covariant_return_type_different_qualifications)
17790 diag::err_covariant_return_type_class_type_more_qualified)
17825 else if (
auto *M = dyn_cast<CXXMethodDecl>(D))
17834 if (
const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
17835 return Var->hasGlobalStorage();
17889 "Parser allowed 'typedef' as storage class of condition decl.");
17895 if (isa<FunctionDecl>(Dcl)) {
17905 if (!ExternalSource)
17909 ExternalSource->ReadUsedVTables(VTables);
17911 for (
unsigned I = 0, N = VTables.size(); I != N; ++I) {
17912 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
17916 if (!Pos->second && VTables[I].DefinitionRequired)
17917 Pos->second =
true;
17921 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
17922 NewUses.push_back(
VTableUse(VTables[I].Record, VTables[I].Location));
17929 bool DefinitionRequired) {
17932 if (!Class->isDynamicClass() || Class->isDependentContext() ||
17940 if (!DefinitionRequired)
17947 Class = Class->getCanonicalDecl();
17948 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator,
bool>
17949 Pos =
VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
17954 if (DefinitionRequired && !Pos.first->second) {
17955 Pos.first->second =
true;
17968 if (Class->hasUserDeclaredDestructor() && !DD->
isDefined()) {
17984 if (Class->isLocalClass())
17987 VTableUses.push_back(std::make_pair(Class, Loc));
17999 bool DefinedAnything =
false;
18000 for (
unsigned I = 0; I !=
VTableUses.size(); ++I) {
18005 Class->getTemplateSpecializationKind();
18009 bool DefineVTable =
true;
18015 if (KeyFunction && !KeyFunction->
hasBody()) {
18017 DefineVTable =
false;
18022 "Instantiations don't have key functions");
18024 }
else if (!KeyFunction) {
18029 bool IsExplicitInstantiationDeclaration =
18031 for (
auto *R : Class->redecls()) {
18033 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
18035 IsExplicitInstantiationDeclaration =
true;
18037 IsExplicitInstantiationDeclaration =
false;
18042 if (IsExplicitInstantiationDeclaration)
18043 DefineVTable =
false;
18049 if (!DefineVTable) {
18057 DefinedAnything =
true;
18070 if (!KeyFunction || (KeyFunction->
hasBody(KeyFunctionDef) &&
18072 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
18077 return DefinedAnything;
18082 for (
const auto *I : RD->
methods())
18083 if (I->isVirtual() && !I->isPure())
18089 bool ConstexprOnly) {
18093 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
18094 E = FinalOverriders.end();
18097 OE = I->second.end();
18099 assert(OI->second.size() > 0 &&
"no final overrider");
18113 for (
const auto &I : RD->
bases()) {
18116 if (
Base->getNumVBases() == 0)
18133 for (
unsigned i = 0; i < ivars.size(); i++) {
18135 if (Field->isInvalidDecl())
18145 InitSeq.
Perform(*
this, InitEntity, InitKind, std::nullopt);
18157 AllToInit.push_back(
Member);
18162 ->getAs<RecordType>()) {
18163 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
18167 PDiag(diag::err_access_dtor_ivar)
18173 AllToInit.data(), AllToInit.size());
18192 (void)
Target->hasBody(FNTarget);
18194 cast_or_null<CXXConstructorDecl>(FNTarget));
18199 *TCanonical =
Target?
Target->getCanonicalDecl() :
nullptr;
18201 if (!Current.insert(Canonical).second)
18206 Target->isInvalidDecl() || Valid.count(TCanonical)) {
18207 Valid.insert(Current.begin(), Current.end());
18210 }
else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
18211 Current.count(TCanonical)) {
18213 if (!Invalid.count(TCanonical)) {
18215 diag::warn_delegating_ctor_cycle)
18219 if (TCanonical != Canonical)
18220 S.
Diag(
Target->getLocation(), diag::note_it_delegates_to);
18223 while (C->getCanonicalDecl() != Canonical) {
18225 (void)C->getTargetConstructor()->hasBody(FNTarget);
18226 assert(FNTarget &&
"Ctor cycle through bodiless function");
18229 cast<CXXConstructorDecl>(FNTarget));
18230 S.
Diag(C->getLocation(), diag::note_which_delegates_to);
18234 Invalid.insert(Current.begin(), Current.end());
18245 for (DelegatingCtorDeclsType::iterator
18251 for (
auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
18252 (*CI)->setInvalidDecl();
18261 explicit FindCXXThisExpr(
Sema &S) : S(S) { }
18289 FindCXXThisExpr Finder(*
this);
18302 if (!Finder.TraverseStmt(E))
18319 FindCXXThisExpr Finder(*
this);
18341 if (!Finder.TraverseType(E))
18351 FindCXXThisExpr Finder(*
this);
18354 for (
const auto *A : Method->
attrs()) {
18356 Expr *Arg =
nullptr;
18358 if (
const auto *G = dyn_cast<GuardedByAttr>(A))
18360 else if (
const auto *G = dyn_cast<PtGuardedByAttr>(A))
18362 else if (
const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
18364 else if (
const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
18366 else if (
const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
18367 Arg = ETLF->getSuccessValue();
18369 }
else if (
const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
18370 Arg = STLF->getSuccessValue();
18372 }
else if (
const auto *LR = dyn_cast<LockReturnedAttr>(A))
18373 Arg = LR->getArg();
18374 else if (
const auto *
LE = dyn_cast<LocksExcludedAttr>(A))
18376 else if (
const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
18378 else if (
const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
18380 else if (
const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
18382 else if (
const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
18385 if (Arg && !Finder.TraverseStmt(Arg))
18388 for (
unsigned I = 0, N = Args.size(); I != N; ++I) {
18389 if (!Finder.TraverseStmt(Args[I]))
18403 Exceptions.clear();
18406 Exceptions.reserve(DynamicExceptions.size());
18407 for (
unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
18414 if (!Unexpanded.empty()) {
18425 Exceptions.push_back(ET);
18435 "Parser should have made sure that the expression is boolean");
18451 Expr *NoexceptExpr) {
18457 MethodD = FunTmpl->getTemplatedDecl();
18467 DynamicExceptionRanges, NoexceptExpr, Exceptions,
18493 Diag(DeclStart, diag::err_anonymous_property);
18518 diag::err_invalid_thread)
18526 switch (
Previous.getResultKind()) {
18533 PrevDecl =
Previous.getRepresentativeDecl();
18546 PrevDecl =
nullptr;
18550 PrevDecl =
nullptr;
18583 if (!ExplicitLists.empty()) {
18584 bool IsMemberSpecialization, IsInvalid;
18588 ExplicitLists,
false, IsMemberSpecialization, IsInvalid,
18591 if (ExplicitParams) {
18592 Info.AutoTemplateParameterDepth = ExplicitParams->
getDepth();
18593 llvm::append_range(Info.TemplateParams, *ExplicitParams);
18594 Info.NumExplicitTemplateParams = ExplicitParams->
size();
18596 Info.AutoTemplateParameterDepth = TemplateParameterDepth;
18597 Info.NumExplicitTemplateParams = 0;
18603 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
18604 if (FSI.NumExplicitTemplateParams != 0) {